将文件中的行保存到新字符串中。 C

Save lines from file into new string. C

我需要将文本文件中的行保存到字符串中,然后将它们插入到数据结构中,但是使用我的解决方案(我认为这真的很糟糕)- 我只将单词保存到我的 line .

    FILE * ifile = fopen("input.txt", "r");
    char line[256];

    while(fscanf(ifile, "%s\n", line) == 1) {
        //inserting "line" into data structure here - no problem with that one
   }

使用 fscanf() 函数几乎总是一个坏主意,因为它会在失败时将文件指针留在未知位置。

您应该使用 fgets() 获取每一行。

#define SIZE_LINE 256
FILE *ifile = fopen ("input.txt", "r");
if (ifile != NULL) {
    while (fgets (buff, SIZE_LINE, ifile)) {
        /* //inserting "line" into data structure here */
    }
    fclose (ifile);
}