【发布时间】:2017-04-21 14:35:51
【问题描述】:
我需要从文件中读取行,但我不知道一行有多长。到目前为止,我唯一能想到的就是使用 fgetc 和 realloc
FILE* cFile = fopen(filename, "r");
....
//some while cycle for going from line to line
....
//now for reading the line itself
char* line = malloc(sizeof(char)); //one empty spot for the '\n'
unsigned int = 0;
char c = getc(cFile);
while (c != '\n') {
line[i] = c;
line = realloc(line, (i+2)*(sizeof(char));
i++;
c = getc(cfile);
}
line[i] = c;
我对 EOL 的所有检查进行了全面检查,或者我是否真的获得了分配的内存,这只是一个示例。
我的问题是,有没有更有效的方法来获得一条未知长度的线?
【问题讨论】:
-
这个
line[0] = c;应该是line[i] = c;。 -
最后的
line[i] = c;应该是line[i] = '\0'; -
“获取未知长度的行”允许黑客压倒计算机的内存资源。防御性编程将确保输入行不超过某个 sane 大小。所以使用一个大缓冲区,如果这还不够,声明一个错误。
-
许多系统使用tentative allocation,因此分配
buf = malloc(1024*1204);并不是内存效率低下。实际内存在使用时分配,不一定在调用*alloc()时分配。 -
@ZergOvermind: '\0' 不是换行符。
标签: c