从文件中读取行不知道线路长度 [英] Read line from file without knowing the line length
问题描述
我想通过文件里逐行读取,不知道之前的线路长度。这是我走到这一步:
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 != '\n' && 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] = '\0'; // newbuffer now contains the line.
我现在可以计算出线路长度,而只是对于那些少于4095个字符,再加上两个char数组线条看起来像是在做任务的尴尬方式。
有没有更好的办法做到这一点(我已经使用与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 count = 0;
int length = 0;
while ( (ch != '\n') && (ch != EOF) ) {
if(count ==CUR_MAX) { // time to expand ?
CUR_MAX *= 2; // expand to double the current size of anything similar.
count = 0;
buffer = realloc(buffer, CUR_MAX); // re allocate memory.
}
ch = getc(file); // read from stream.
buffer[length] = ch; // stuff in buffer.
length++;
count++;
}
.
.
free(buffer);
您必须调用后检查分配错误的malloc
和的realloc
。
You'll have to check for allocation errors after calls to malloc
and realloc
.
这篇关于从文件中读取行不知道线路长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!