C:读取单词并在其上包含\ n,但不包括空格

时间:2013-07-10 13:59:17

标签: c string file fgets scanf

我需要读取C中的文件并将每个单词放在数组中, 空格不应该包含在单词中(当它到达一个空格时它应该结束复制该单词),但是\ n必须包含它。

fscanf(arquivo,"%s",palavras[i].string);

几乎正常工作,但是当文件中找到它时,它不包括\ n

fgets (temp , 100 , arquivo);

不起作用,因为它找不到空格时不会停止。

你们有什么想法?

4 个答案:

答案 0 :(得分:0)

在这种情况下,

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
}

答案 1 :(得分:0)

如果您想使用fscanf,可以使用以下内容:

fscanf(fp, "%[^ ]", str);

答案 2 :(得分:0)

您可以使用fgetssscanf的组合,

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来保持线条。当然,需要更多的错误检查才能使其稳定。

答案 3 :(得分:0)

我会采取不同的方法。

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++;
         }
     }
}

这将创建一个字符数组(或字符串)数组,并为每个数组添加字符,直到找到一个空格,在这种情况下,它将跳过它并继续下一个字符并开始一个新字符串。