Development

Get File Size in C

In this guide, we will cover the methods that allows us to fetch the file size in the C programming language.
Captain Salem 4 min read
Get File Size in C

File operation is a common task for any developer, regardless of the target language. This is because interacting with the file system is a fundamental part of creating and working with efficient programs.

One of the most common file operations tasks involves fetching the size of a given file. This can range from just needing to know the file size, memory allocation, data processing, disk usage, file system modifications, etc.

We will try to stick to the most common methods and how each of them works with an example.

Method 1 - Using fseek() and ftell() Functions

The most common and fundamental method that we can use to fetch the size of files is the fseek() and ftell() functions from the C standard library.

Let us start with fseek(). The function syntax is as shown:

int fseek(FILE *stream, long int offset, int whence);

The function accepts the following parameters.

  • stream - refers to a pointer to the FILE object representing the file stream you want to set the position within.
  • offset - A long integer that specifies the number of bytes to move the file position indicator. A positive value moves it forward, and a negative value moves it backward.
  • whence - sets an integer that specifies the reference point from which the offset is applied. It can take one of the following values:The function allows us to set the file position indicator for a given file stream.
    • SEEK_SET - The offset is relative to the beginning of the file.
    • SEEK_CUR - The offset is relative to the current position of the file pointer.
    • SEEK_END - The offset is relative to the end of the file.

Next, we have the ftell().

The function allows us to current file position indicator for a given file stream. It returns the current position as a long integer which represents the offset in bytes from the beginning of the file.

The function syntax is as shown:

long int ftell(FILE *stream);
  • stream - A pointer to the FILE object representing the file stream for which you want to determine the current position.

We can use both of these functions to to get the size of a file as shown:

#include <stdio.h>

int main() {
    FILE *file = fopen("duplicate.svg", "rb");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }

    fseek(file, 0, SEEK_END);
    long size = ftell(file);
    fclose(file);

    printf("File size: %ld bytes\n", size);
    return 0;
}

In the code abvoe, we start by opening the file in binary read mode using the fopen() function.

We then use the fseek() function to move the file pointer to the end of the file. Lastly, we use the ftell() functin to retreive the current position of the file which is the file size.

Compile:

gcc size.c

Output:

File size: 932 bytes

Method 2 - Using the stat() Function

From the standard lib, we have the stat() function that allows us to fetch file information which includes the file size.

The main drawback of this method is that it is platform-dependent. Hence, it will only work on Unix-based systems.

The function syntax is as shown:

int stat(const char *path, struct stat *buf);

The function parameters are as shown:

  • path - refers to a pointer to a null-terminated string that specifies the path to the file or directory.
  • buf - A pointer to a struct stat object where the file information will be stored.

The stat function fills the struct stat with information about the file specified by path. We can then access the various attributes of the file, such as its size, using members of the struct stat.

These include:

  • st_size- The size of the file in bytes.
  • st_mode - File mode and permissions.
  • st_mtime - The last modification timestamp.
  • st_ctime - The last status change timestamp (e.g., file permissions change).
  • st_atime - The last access timestamp.

The following example shows how to use the stat() function to fetch the file size:

#include <stdio.h>
#include <sys/stat.h>

int main() {
    struct stat fileStat;
    if (stat("duplicate.svg", &fileStat) == -1) {
        perror("Error getting file information");
        return 1;
    }

    printf("File size: %lld bytes\n", (long long)fileStat.st_size);
    return 0;
}

Output:

File size: 932 bytes

Method 3 - Using the Windows API

If we want to use this on a windows system, we might as well take advantage of the provided windows API features to retrieve the file size.

NOTE: It is good to keep in mind that this method will only work on Windows based systems.An example is as shown below:

#include <stdio.h>
#include <windows.h>

int main() {
    WIN32_FILE_ATTRIBUTE_DATA fileAttr;
    if (!GetFileAttributesEx("duplicate.svg", GetFileExInfoStandard, &fileAttr)) {
        perror("Error getting file information");
        return 1;
    }

    ULONGLONG size = ((ULONGLONG)fileAttr.nFileSizeHigh << 32) | fileAttr.nFileSizeLow;
    
    printf("File size: %llu bytes\n", size);
    return 0;
}

In the example above, we start by including the required headers, in this case, we need the windows.h header file which contains Windows related functions and tools.

We then use the GetFileAttributesEx() to retrieve file attributes, including size. Lastly, we combine nFileSizeHigh and nFileSizeLow to get the complete file size.

Method 4 - POSIX

On Unix-like systems, we cna POSIX specific functions to get the file size as shown in the example below:

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int main() {
    struct stat fileStat;
    if (stat("duplicate.svg", &fileStat) == -1) {
        perror("Error getting file information");
        return 1;
    }

    off_t size = fileStat.st_size;
    
    printf("File size: %lld bytes\n", (long long)size);
    return 0;
}

In this example, we include the required header file for POSIX functions and use the stat() method. SImilar to the previous steps.

Conclusion

In this tutorial, we learned how we can use and work with various methods in C to get the size of a file in bytes depending on the platform.

Share
Comments
More from GeekBits

Join us at GeekBits

Join our members and get a currated list of awesome articles each month.

Great! You’ve successfully signed up.

Welcome back! You've successfully signed in.

You've successfully subscribed to GeekBits.

Success! Check your email for magic link to sign-in.

Success! Your billing info has been updated.

Your billing was not updated.