如何从c / c ++中的文本文件中读取一行?

经过详尽的谷歌搜索和访问许多论坛,我还没有找到一个很好的综合答案这个问题。 很多论坛建议使用get line istream& getline (char* s, streamsize n )函数。 我的问题是,如果我不知道每条线的长度是多少,并且无法预测尺寸可能是什么? 它在C中的等价物是什么?

c / c ++中是否有任何特定的函数每次从文本文件中读取一行?

解释,使用代码片段将对我有所帮助。

在c中,你可以使用fopen和getch。 通常,如果你不能确切地确定最长线的长度,你可以分配一个大的缓冲区(例如8kb)并且几乎可以保证获得所有线路。

如果你有可能真的有很长的线条并且你必须逐行处理,你可以使用malloc一个合理的缓冲区,并且每当你接近填充它时使用realloc来加倍它的大小。

 #include  #include  void handle_line(char *line) { printf("%s", line); } int main(int argc, char *argv[]) { int size = 1024, pos; int c; char *buffer = (char *)malloc(size); FILE *f = fopen("myfile.txt", "r"); if(f) { do { // read all lines in file pos = 0; do{ // read one line c = fgetc(f); if(c != EOF) buffer[pos++] = (char)c; if(pos >= size - 1) { // increase buffer length - leave room for 0 size *=2; buffer = (char*)realloc(buffer, size); } }while(c != EOF && c != '\n'); buffer[pos] = 0; // line is now in buffer handle_line(buffer); } while(c != EOF); fclose(f); } free(buffer); return 0; } 

在C ++中,您可以使用全局函数std :: getline,它接受一个字符串,一个流和一个可选的分隔符,并读取1行,直到达到指定的分隔符。 一个例子:

 #include  #include  #include  int main() { std::ifstream input("filename.txt"); std::string line; while( std::getline( input, line ) ) { std::cout< 

该程序从文件中读取每一行并将其回显到控制台。

对于C你可能正在考虑使用fgets ,因为我使用C已经有一段时间了,这意味着我有点生疏,但我相信你可以使用它来模拟上述C ++程序的function,如下所示:

 #include  int main() { char line[1024]; FILE *fp = fopen("filename.txt","r"); //Checks if file is empty if( fp == NULL ) { return 1; } while( fgets(line,1024,fp) ) { printf("%s\n",line); } return 0; } 

由于限制,该行不能长于您正在读取的缓冲区的最大长度。

在C,fgets()中,您需要知道最大大小以防止截断。

我不是很擅长C,但我相信这段代码应该让你完整的单行直到最后……

  #include int main() { char line[1024]; FILE *f=fopen("filename.txt","r"); fscanf(*f,"%[^\n]",line); printf("%s",line); } 

getline()正是你要找的。 您在C ++中使用字符串,并且您不需要提前知道大小。

假设std命名空间:

  ifstream file1("myfile.txt"); string stuff; while (getline(file1, stuff, '\n')) { cout << stuff << endl; } file1.close();