c - C,读取多行文本文件

标签 c file text multiline

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

while (!feof(in)) {
    fscanf(in,"%s %s %s \n",string1,string2,string3);
}


^^这是我从一行加载数据的方式,并且工作正常。我只是不知道如何从第二行和第三行加载相同的数据。

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

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

最佳答案

尝试类似的方法:

/编辑/

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 */


甚至...

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

关于c - C,读取多行文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5827931/

相关文章:

javascript - 获取选定文本的父元素

c - 在 C 中找到字符最右边的出现?

mysql - 指针类型与 mysql_store_result 不兼容

c# - 流不写入文件

java - 无法使用 FileInputStream 复制 PDF 文件

swift - 按钮上的文字不正确

c - 将文本文件的每一行转换为数组 c

在共享内存中创建和访问结构

c - 解析字符串,忽略相对位置中的空格 - sscanf

c - mmap MAP_SHARED 不工作