Read file contents with unknown size
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
}开发者_StackOverflow中文版
fstat(fileno(fp), &st);
fread(buffer, sizeof(char), st.st_size, fp);
fprintf(stderr, "%s\n", *buffer);
fclose(fp);
I have read that a bus error can be caused by a buffer overflow. I am pretty sure I am getting a buffer overflow with my char *buffer
. But then, how can I specify the size of the buffer at runtime?
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.
Use malloc(3)
. Put:
buffer = malloc(st.st_size);
Before your call to fread()
. Don't forget to free buffer
when you're done with it!
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.
You can allocate memory with malloc
:
buffer = malloc(number_of_bytes_to_allocate);
if(buffer == NULL) {
// error allocating memory
}
free
when you're done with it!
free(buffer);
In C99, and assuming your config file should not be in the MiB or larger range, you could use a VLA:
FILE *fp = fopen(CONFIG_FILE, "r");
if (fp == NULL) {
// error handling and cleanup omitted for brevity
}
struct stat st;
fstat(fileno(fp), &st); // Error check omitted
char buffer[st.st_size+1];
fread(buffer, sizeof(char), st.st_size, fp);
buffer[st.st_size] = '\0';
fprintf(stderr, "%s\n", *buffer);
fclose(fp);
精彩评论