[英]Save lines from file into new string. C
I need to save lines from a text file into a string and then insert them into a data structure, but with my solution (which I assume is really bad) - I only save words into my line
. 我需要将文本文件中的行保存到字符串中,然后将它们插入到数据结构中,但是我的解决方案(我认为这非常糟糕) - 我只将单词保存到我的
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
}
It's almost always a bad idea to use the fscanf() function as it can leave your file pointer in an unknown location on failure. 使用fscanf()函数几乎总是一个坏主意,因为它可能会在失败时将文件指针留在未知位置。
You should use fgets() to get each line. 您应该使用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.