Search code examples
cfilemalloceoffeof

determine size of file for buffer allocation in c


This snippet of code I wrote is supposed to traverse through a file and increment the size-counter each-time it goes +1 character:

while (fgetc(input) != EOF)
    size++; 

if (feof(input)) {
    buff = (char *)malloc(sizeof(char) * size + 1); 
}

while the end of the file is not reached size is being incremented. If EOF-> feof==true and the the buffer-size can be determined.

Just wanted to know if it is possible that way or if there are better ways to do it.


Solution

  • Assuming size is initialized to 0 before the loop and input is at the beginning of the stream, the loop will correctly determine the number of bytes that can be read from the file.

    Testing for feof() after the loop distinguishes end-of-file and read-error conditions. It is usually not necessary to make this distinction, so you can remove this test.

    malloc(sizeof(char) * size + 1) allocates the correct number of bytes to read the file as a C string, but the expression is incorrect: it should be either sizeof(char) * (size + 1) or just size + 1 as sizeof(char) is 1 by definition.

    Note that you will need to set the null terminator explicitly as malloc() does not initialize the block it allocate.

    Note also the some streams, such a terminals, may not be seekable, so this method may fail if you need to rewind the stream to read the bytes.

    Note finally that size may be smaller than the length of the file on legacy systems that use 2 bytes for end of line markers such as MS/DOS and Windows.