阅读与未知大小的文件内容 [英] Read file contents with unknown size
问题描述
我想处理一个配置文件的内容。该配置文件可以是任何大小。我得到一个总线错误,程序挂起后,当我运行下面的code:
I want to process the contents of a config file. The config file could be any size. I am getting a Bus Error, after the program hangs, when I run the following code:
FILE *fp;
struct stat st;
char *buffer;
fp = fopen(CONFIG_FILE, "r");
if (fp == NULL) {
// error handling and cleanup omitted for brevity
}
fstat(fileno(fp), &st);
fread(buffer, sizeof(char), st.st_size, fp);
fprintf(stderr, "%s\n", *buffer);
fclose(fp);
我已阅读,总线错误可能由一个缓冲区溢出引起的。我是pretty确保我得到一个缓冲区溢出我的的char *缓冲区
。但随后,我怎么能在运行时指定缓冲区的大小?
修改 - 总线错误是由我在电话的fread硬编码 1
的懒惰造成的。在code例如已更新来解决这个问题,使用的sizeof(char)的
代替。
EDIT - The bus error was caused by my laziness of hardcoding 1
in the fread call. The code example has been updated to fix this, using sizeof(char)
instead.
推荐答案
使用 的malloc(3)
。认沽:
Use malloc(3)
. Put:
buffer = malloc(st.st_size);
您的来电 FREAD前()
。不要忘了在缓存
当你用它做!
Before your call to fread()
. Don't forget to free buffer
when you're done with it!
您可能不希望在你的使用
通话,无论是。如果你打算尝试打印整个文件那样,你会希望确保分配一个额外的字节为空,终止您的字符串。 *缓冲区
的printf()
You probably don't want to use *buffer
in your printf()
call, either. If you're going to try to print the whole file like that, you will want to make sure to allocate an extra byte to null-terminate your string.
这篇关于阅读与未知大小的文件内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!