繁体   English   中英

将文件中的行保存为新字符串。 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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM