我需要从 C 中的文件中读取并将每个单词放在一个数组中,单词中不应包含空格(当它到达空格时,它应该结束复制该单词),但 \n 必须在找到时包含。
fscanf(arquivo,"%s",palavras[i].string);
几乎可以工作,但是在文件中找到它时不包括 \n ..
fgets (temp , 100 , arquivo);
不起作用,因为它在找到空间时不会停止。
你们有什么感想?
我会对此采取不同的方法。
int fd,i,j=0;;
fd = open("nameoffile",O_RDONLY);
char buf[128], word[64];
char *words[128];
while (n=read(fd,buf,sizeof(buf))){
memset(word,0,sizeof(word));
for (i=0;i<n;i++){
if (buf[i] != ' ') word[i] = buf[i];
else {
words[j] = malloc(sizeof(word));
words[j] = word;
j++;
}
}
}
这将创建一个字符数组(或字符串)数组,并向每个数组添加字符,直到找到一个空格,在这种情况下,它将跳过它并移动到下一个字符并开始一个新字符串。
你可以使用fgets
和sscanf
喜欢的组合,
ptr = NULL;
ptr = fgets (temp , 100 , arquivo);
// Check 1) return value for NULL 2) whether temp has `\n`
// or read till `\n`
while( ( found = sscanf( ptr, "%s", palavras[i].string ) ) == 1 )
{
// palavras[i].string has valid string
ptr += strlen( palavras[i].string ); // next string in
i++; // next element in array. Overflowing ?
}
strcat( palavras[i].string, "\n" );
提供足够的尺寸fgets
以保持线。当然,需要更多的错误检查才能使其稳定。
如果要使用 fscanf,可以使用以下命令:
fscanf(fp, "%[^ ]", str);
fscanf
在这种情况下,当它到达任何类型的空格(包括换行符)时会停止。您可以尝试使用fgets
来读取整行(包括换行符),然后strtok
反复使用来分解它。
例如:
char temp[100];
char *tok;
fgets (temp , 100 , arquivo);
while ((tok = strtok(temp, " ")) != NULL) {
// 'tok' points to a null-terminated word with no spaces
}