This post will discuss how to find the size of a file in bytes in C.

The Standard C doesn’t provide any direct method to determine the size of the file. However, we can use any of the following methods to get the file size:

1. Using stat() function

On Unix-like systems, we can use POSIX-compliant system calls. The stat() function takes the file path and returns a structure containing information about the file pointed by it. To get the size of the file in bytes, use the st_size field of the returned structure.

2. Using fstat() function

If we already have a file descriptor, use the fstat() function. The fstat() function is identical to the stat() function, except that the file is specified by the file descriptor.

3. Using fseek() function

The idea is to seek the file to the end using the fseek() function with the SEEK_END offset, and then get the current position using the ftell() function. The return value by ftell() is the file size in bytes.

This approach is demonstrated below. Note that after getting the file size, we’re calling the rewind() function to seek the file to the beginning of the file. The rewind() function is equivalent to calling fseek(stream, 0L, SEEK_SET).

That’s all about finding the size of a file in bytes in C.