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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3081289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 12:00:56  来源:igfitidea点击:

How to read a line from a text file in c/c++?

c++c

提问by Eternal Learner

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?

经过详尽的谷歌搜索和访问许多论坛后,我还没有找到这个问题的一个很好的综合答案。很多论坛都建议使用 get line 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.

解释,代码片段对我有很大帮助。

回答by Jacob

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,它接受一个字符串、一个流和一个可选的分隔符,并读取 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;
}

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.

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

回答by sje397

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

回答by ninjalj

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

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

回答by Nagarjuna Yendluri

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

回答by Xorlev

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();