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

Ete*_*ner 16 c c++

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

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

解释,使用代码片段将对我有很大帮助.

Jac*_*cob 22

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

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

int main() {
    std::ifstream input("filename.txt");
    std::string line;

    while( std::getline( input, line ) ) {
        std::cout<<line<<'\n';
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

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

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

#include <stdio.h>

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;
}
Run Code Online (Sandbox Code Playgroud)

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


sje*_*397 18

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

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

#include <stdio.h>
#include <stdlib.h>

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;
}
Run Code Online (Sandbox Code Playgroud)


nin*_*alj 7

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


Xor*_*lev 5

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

假设 std 命名空间:

 ifstream file1("myfile.txt");
 string stuff;

 while (getline(file1, stuff, '\n')) {
      cout << stuff << endl;
 }

 file1.close();
Run Code Online (Sandbox Code Playgroud)

  • 我们将如何在 C 中做到这一点? (3认同)

小智 5

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

 #include<stdio.h>

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

  • 您应该避免“fscanf”,因为它会导致缓冲区溢出。它现在提供了将输入大小限制为写入缓冲区(此处为“行”)大小的方法。 (2认同)