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

时间:2021-03-11 00:35:32

This question already has an answer here:

这个问题已经有了答案:

After exhaustive googling and visiting many forums, I am yet to find a good comprehensive answer for this question. A lot of the forums suggest using the get line istream& getline (char* s, streamsize n ) function. My question is what if I don't know what the length of each line is and cannot predict what the size may be? Also what is it's equivalent in C?

在彻底搜索和访问了许多论坛之后,我还没有找到一个很好的全面的答案来回答这个问题。许多论坛建议使用getline istream&getline (char* s, streamsize n)函数。我的问题是,如果我不知道每条线的长度是什么,不能预测它的大小?它在C中的等价性是什么?

Is there any specific function in c /c++ to read one single line each time from a text file ?

在c /c++中是否有特定的函数可以从文本文件中读取一行?

Explanation , with Code snippets will help me a lot.

解释,用代码段可以帮助我很多。

5 个解决方案

#1


18  

In c, you could use fopen, and getch. Usually, if you can't be exactly sure of the length of the longest line, you could allocate a large buffer (e.g. 8kb) and almost be guaranteed of getting all lines.

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

If there's a chance you may have really really long lines and you have to process line by line, you could malloc a resonable buffer, and use realloc to double it's size each time you get close to filling it.

如果有机会,您可能有非常长的行,并且您必须按一行来处理,您可以malloc一个可共鸣的缓冲区,并使用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;
}

#2


22  

In C++, you can use the global function std::getline, it takes a string and a stream and an optional delimiter and reads 1 line until the delimiter specified is reached. An example:

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

#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;
}

This program reads each line from a file and echos it to the console.

这个程序读取文件中的每一行,并将其与控制台相呼应。

For C you're probably looking at using fgets, it has been a while since I used C, meaning I'm a bit rusty, but I believe you can use this to emulate the functionality of the above C++ program like so:

对于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;
}

With the limitation that the line can not be longer than the maximum length of the buffer that you're reading in to.

有了限制,这条线的长度不能超过你读到的缓冲区的最大长度。

#3


7  

In C, fgets(), and you need to know the maximum size to prevent truncation.

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

#4


4  

im not really that good at C , but i believe this code should get you complete single line till the end...

我不是很擅长C语言,但我相信这段代码应该能让你完成一行,直到最后……

 #include<stdio.h>

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

#5


3  

getline() is what you're looking for. You use strings in C++, and you don't need to know the size ahead of time.

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

Assuming std namespace:

假设std命名空间:

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

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

 file1.close();

#1


18  

In c, you could use fopen, and getch. Usually, if you can't be exactly sure of the length of the longest line, you could allocate a large buffer (e.g. 8kb) and almost be guaranteed of getting all lines.

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

If there's a chance you may have really really long lines and you have to process line by line, you could malloc a resonable buffer, and use realloc to double it's size each time you get close to filling it.

如果有机会,您可能有非常长的行,并且您必须按一行来处理,您可以malloc一个可共鸣的缓冲区,并使用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;
}

#2


22  

In C++, you can use the global function std::getline, it takes a string and a stream and an optional delimiter and reads 1 line until the delimiter specified is reached. An example:

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

#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;
}

This program reads each line from a file and echos it to the console.

这个程序读取文件中的每一行,并将其与控制台相呼应。

For C you're probably looking at using fgets, it has been a while since I used C, meaning I'm a bit rusty, but I believe you can use this to emulate the functionality of the above C++ program like so:

对于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;
}

With the limitation that the line can not be longer than the maximum length of the buffer that you're reading in to.

有了限制,这条线的长度不能超过你读到的缓冲区的最大长度。

#3


7  

In C, fgets(), and you need to know the maximum size to prevent truncation.

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

#4


4  

im not really that good at C , but i believe this code should get you complete single line till the end...

我不是很擅长C语言,但我相信这段代码应该能让你完成一行,直到最后……

 #include<stdio.h>

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

#5


3  

getline() is what you're looking for. You use strings in C++, and you don't need to know the size ahead of time.

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

Assuming std namespace:

假设std命名空间:

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

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

 file1.close();