2015-06-28 53 views
1

我需要将文本文件中的行保存到一个字符串中,然后将它们插入到数据结构中,但是使用我的解决方案(我认为它非常糟糕) - 我只会将文字保存到我的line中。将文件中的行保存到新字符串中。 C

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

'“%s \ n”' - >'“%[^ \ n]”' –

回答

3

这几乎总是一个坏主意,使用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); 
} 
+0

非常感谢! – Megabight

+1

哦,我做到了,但我需要赢得更多的声望才能让它数数或者什么...... – Megabight

相关问题