C,读取多行文本文件

时间:2011-04-29 04:35:01

标签: c file text multiline

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

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

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

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

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

5 个答案:

答案 0 :(得分:4)

尝试类似:

/编辑/

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

答案 1 :(得分:3)

\n放在scanf格式字符串中与空格没有什么不同。您应该使用fgets来获取该行,然后使用sscanf来获取该字符串本身。

这也允许更容易的错误恢复。如果只是匹配换行符,则可以在字符串末尾使用"%*[ \t]%*1[\n]"而不是" \n"。在这种情况下,您应该使用%*[ \t]代替所有空格,并检查fscanf的返回值。直接在输入上使用fscanf很难做到正确(如果一行上有四个单词怎么办?如果只有两个单词会怎么样?)我会推荐fgets / sscanf解决方案。

此外,正如Delan Azabani所说......从这个片段中不清楚你是否还没有这样做,但是你必须要么定义空间[例如在一个大型数组或一些动态结构中使用malloc]来存储整个数据集,或者在循环中进行所有处理。

您还应该为格式说明符中的每个字符串指定可用空间。 <{1}}本身在scanf中始终是一个错误,可能是一个安全漏洞。

答案 2 :(得分:2)

首先,你不要那样使用feof() ......它显示了一个可能的Pascal背景,无论是你过去还是你老师的过去。

对于阅读行,最好使用POSIX 2008(Linux)getline()或标准C fgets()。无论哪种方式,您尝试使用该函数读取该行,并在其指示EOF时停止:

while (fgets(buffer, sizeof(buffer), fp) != 0)
{
     ...use the line of data in buffer...
}

char *bufptr = 0;
size_t buflen = 0;
while (getline(&bufptr, &buflen, fp) != -1)
{
    ...use the line of data in bufptr...
}
free(bufptr);

要读取多行,您需要确定是否还需要以前的行。如果没有,单个字符串(字符数组)将执行。如果你需要前面的行,那么你需要读入一个数组,可能是一个动态分配的指针数组。

答案 3 :(得分:1)

每次拨打fscanf时,都会读取更多值。你现在遇到的问题是你将每一行重新读入相同的变量,所以最后,这三个变量都有最后一行的值。尝试创建一个可以容纳所需值的数组或其他结构。

答案 4 :(得分:0)

我有一个更简单的解决方案,没有令人费解的令人困惑的方法片段(没有违反上述规定)这里是:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;
int main()
{
    string line;//read the line
    ifstream myfile ("MainMenu.txt"); // make sure to put this inside the project folder with all your .h and .cpp files

    if (myfile.is_open())
    {
        while ( myfile.good() )
        {
            getline (myfile,line);
            cout << line << endl;
        }
        myfile.close();
           }
    else cout << "Unable to open file";
   return 0;

}

快乐编码