我正在编写一个需要逐行解析配置文件的函数。
我基本上有 3 种方法可以从这里开始,我正处于将一行读入内存的阶段:
读取一行中的字符数量,
fseek()
回到行首,malloc()
缓冲区,将行读入内存读取行中的字符并为每个添加字符
realloc()
“猜测”一个合理的行长度,并且只有在超过该长度时才
realloc()
。
在这个阶段时间并不是很重要,所以 1 毫秒还是半秒并不重要,但我希望有被认为是最好的解决方案。
过去我使用过解决方案 1,因为我不太喜欢调用 realloc()
可能数百次。
什么是最佳实践?
e/
一些进一步的解释:
我的配置文件看起来像这样
键=值#评论
我在阅读过程中将 =
字符替换为 \0
字符并跟踪偏移量。然后我 strcompare()
我正在寻找的配置标签行,一旦找到匹配的配置标签,我将值移动到数组的开头并进行后处理(atoi ()
, strtoull()
之类的东西)然后放到另一个变量中。之后,我释放我的阅读行并转到下一行。
当我读字符的时候。我跳过空格,#
之后的所有内容都不会被读入内存。所以在 99% 的情况下,我的整个 key=value 字符串都是 <64 字节。
最佳答案
与其分配一个小缓冲区并频繁地重新分配,不如分配一个大缓冲区并重新分配到所需的确切大小。也许这样的事情会奏效?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char *getinput ( ) {
char *input;
input = malloc ( 1000); // allocate a large buffer
fgets (input, 1000, stdin);
// may need to set a '\0' somewhere in input...
input = realloc ( input, strlen(input) + 1); // realloc to exact size
return input;
}
int main()
{
char *output[10];
int counter = 0;
while ( counter < 10) {
output[counter] = getinput();
printf ( "%s\n", output[counter]);
counter++;
}
counter = 0;
while ( counter < 10) {
printf ( "\t%s\n", output[counter]);
free ( output[counter]);
counter++;
}
return 0;
}
关于c - 额外的文件访问或大量的重新分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24919969/