How can I get a file"s size in C?

Matheus Mello
Matheus Mello
September 2, 2023
Cover Image for How can I get a file"s size in C?

📁 How to Get a File's Size in C 🤔

So, you're coding in C and wondering how to find the size of a file? Don't worry, we've got you covered! Knowing the size of a file is essential, especially if you want to allocate memory dynamically using malloc() or perform any file operations.

🧐 The Common Issue

Let's dive into the problem you encountered. You have a file you opened in your C application and you want to determine its size. This is especially useful if you plan to load the file content into a string, allocated using malloc(). After all, just blindly allocating memory with something like malloc(10000*sizeof(char)); is simply not the way to go.

💡 The Easy Solutions

Thankfully, there are a couple of easy ways to get the size of a file in C. Here are our top two recommendations:

1. Using fseek() and ftell()

#include <stdio.h>

long getFileSize(FILE *file) {
    long size;

    fseek(file, 0, SEEK_END);  // Move the file pointer to the end of the file
    size = ftell(file);  // Get the current position of the file pointer (which is the file size)
    rewind(file);  // Reset the file pointer to the beginning of the file

    return size;
}

int main() {
    FILE *file = fopen("your_file.txt", "r");
    if (file != NULL) {
        long size = getFileSize(file);
        printf("The file size is %ld bytes.\n", size);
        fclose(file);
    }

    return 0;
}

Here, we define a function getFileSize() that takes a FILE* as an argument and returns the size of the file. We achieve this by moving the file pointer to the end of the file using fseek() with the SEEK_END constant. Then, we retrieve the current position of the file pointer using ftell(), which gives us the file size. Finally, we rewind the file pointer back to the beginning of the file using rewind() to avoid any unexpected behavior in subsequent file operations.

2. Using stat()

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

long getFileSize(const char *filename) {
    struct stat st;

    if (stat(filename, &st) == 0)
        return st.st_size;

    return -1;  // Error occurred
}

int main() {
    const char *filename = "your_file.txt";
    long size = getFileSize(filename);

    if (size != -1)
        printf("The file size is %ld bytes.\n", size);
    else
        printf("Error occurred while getting the file size.\n");

    return 0;
}

Using stat(), we obtain and store file information in a struct stat. The st_size field of the structure contains the file's size. Simple, right?

🔥 The Compelling Call-to-Action

With these two easy-to-implement solutions, finding the size of a file in your C application shouldn't be a daunting task anymore. Choose the approach that suits your needs best, and feel free to experiment and explore further possibilities.

Have you encountered any other file-related issues or have more C-related questions? Leave a comment below and let's continue the conversation! Happy coding! 😄👨‍💻💬

Take Your Tech Career to the Next Level

Our application tracking tool helps you manage your job search effectively. Stay organized, track your progress, and land your dream tech job faster.

Your Product
Product promotion

Share this article

More Articles You Might Like

Latest Articles

Cover Image for How can I echo a newline in a batch file?
batch-filenewlinewindows

How can I echo a newline in a batch file?

Published on March 20, 2060

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Cover Image for How do I run Redis on Windows?
rediswindows

How do I run Redis on Windows?

Published on March 19, 2060

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Cover Image for Best way to strip punctuation from a string
punctuationpythonstring

Best way to strip punctuation from a string

Published on November 1, 2057

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Cover Image for Purge or recreate a Ruby on Rails database
rakeruby-on-railsruby-on-rails-3

Purge or recreate a Ruby on Rails database

Published on November 27, 2032

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my