在不知道行长的情况下从文件中读取行 [英] Read line from file without knowing the line length

查看:17
本文介绍了在不知道行长的情况下从文件中读取行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想逐行读入文件,之前不知道行长.这是我到目前为止所得到的:

I want to read in a file line by line, without knowing the line length before. Here's what I got so far:

int ch = getc(file);
int length = 0;
char buffer[4095];

while (ch != '
' && ch != EOF) {
    ch = getc(file);
    buffer[length] = ch;
    length++;
}

printf("Line length: %d characters.", length);

char newbuffer[length + 1];

for (int i = 0; i < length; i++)
    newbuffer[i] = buffer[i];

newbuffer[length] = '';    // newbuffer now contains the line.

我现在可以计算出行长,但仅限于短于 4095 个字符的行,加上两个字符数组似乎是一种笨拙的完成任务的方式.有没有更好的方法来做到这一点(我已经使用过 fgets() 但被告知这不是最好的方法)?

I can now figure out the line length, but only for lines that are shorter than 4095 characters, plus the two char arrays seem like an awkward way of doing the task. Is there a better way to do this (I already used fgets() but got told it wasn't the best way)?

--Ry

推荐答案

你可以从你选择的一些合适的大小开始,如果你需要更多空间,然后在中间使用 realloc :

You can start with some suitable size of your choice and then use realloc midway if you need more space as:

int CUR_MAX = 4095;
char *buffer = (char*) malloc(sizeof(char) * CUR_MAX); // allocate buffer.
int length = 0;

while ( (ch != '
') && (ch != EOF) ) {
    if(length ==CUR_MAX) { // time to expand ?
      CUR_MAX *= 2; // expand to double the current size of anything similar.
      buffer = realloc(buffer, CUR_MAX); // re allocate memory.
    }
    ch = getc(file); // read from stream.
    buffer[length] = ch; // stuff in buffer.
    length++;
}
.
.
free(buffer);

您必须在调用 mallocrealloc 后检查分配错误.

You'll have to check for allocation errors after calls to malloc and realloc.

这篇关于在不知道行长的情况下从文件中读取行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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