如何阅读在C / C文本文件中的行++? [英] How to read a line from a text file in c/c++?

查看:74
本文介绍了如何阅读在C / C文本文件中的行++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Google上搜寻详尽和来访的许多论坛上,我还没有找到这个问题的一个很好的融为一体prehensive答案。很多论坛的建议使用get线
的IStream&安培;函数getline(字符* S,streamsize可N)功能。我的问题是,如果我不知道每行的长度是多少,不能predict大小可能是什么?另外它是什么在C相同呢?

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?

有没有在C / C ++的特定功能来读取文本文件每次一单行?

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

解释,并code段将帮助我很多东西。

Explanation , with Code snippets will help me a lot.

推荐答案

在C,你可以使用的fopen,和残培。通常,如果你不能完全确定的最长行的长度,你可以分配一个大的缓冲区(例如8KB),几乎保证让所有的行。

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.

如果有一个机会,你可能真的很长的线,你必须处理一行行,你可以MALLOC一个合理的缓冲,并使用realloc的加倍它的大小每次接近填充它的时间。

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.

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

这篇关于如何阅读在C / C文本文件中的行++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆