C、读取多行文本文件

JC *_*yba 6 c text file multiline

我知道这是一个愚蠢的问题,但是如何从多行文本文件加载数据?

while (!feof(in)) {
    fscanf(in,"%s %s %s \n",string1,string2,string3);
}
Run Code Online (Sandbox Code Playgroud)

^^这就是我从单行加载数据的方法,它工作得很好。我只是不知道如何从第二行和第三行加载相同的数据。

我再次意识到这可能是一个愚蠢的问题。

编辑:问题没有解决。我不知道如何从不在第一行的文件中读取文本。我该怎么做?抱歉问了这个愚蠢的问题。

jim*_*man 9

尝试类似的方法:

/编辑/

char line[512]; // or however large you think these lines will be

in = fopen ("multilinefile.txt", "rt");  /* open the file for reading */
/* "rt" means open the file for reading text */
int cur_line = 0;
while(fgets(line, 512, in) != NULL) {
     if (cur_line == 2) { // 3rd line
     /* get a line, up to 512 chars from in.  done if NULL */
     sscanf (line, "%s %s %s \n",string1,string2,string3);
     // now you should store or manipulate those strings

     break;
     }
     cur_line++;
} 
fclose(in);  /* close the file */
Run Code Online (Sandbox Code Playgroud)

或者甚至...

char line[512];
in = fopen ("multilinefile.txt", "rt");  /* open the file for reading */
fgets(line, 512, in); // throw out line one

fgets(line, 512, in); // on line 2
sscanf (line, "%s %s %s \n",string1,string2,string3); // line 2 is loaded into 'line'
// do stuff with line 2

fgets(line, 512, in); // on line 3
sscanf (line, "%s %s %s \n",string1,string2,string3); // line 3 is loaded into 'line'
// do stuff with line 3

fclose(in); // close file
Run Code Online (Sandbox Code Playgroud)