Read file contents with unknown size

后端 未结 3 366
小鲜肉
小鲜肉 2021-01-14 11:44

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:

3条回答
  •  死守一世寂寞
    2021-01-14 12:17

    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.

提交回复
热议问题