How Big is That File?

Difficulty: ★ ★ ☆ ☆

The stat() function returns various tidbits about a file, including its timestamp, permissions, file type, and the file’s size in bytes. This value can also be obtained without without using the stat() function, which is this month’s Exercise.

I suppose I could stop writing this post with that last paragraph, wish you good luck and make this the shortest Exercise post in the blog’s history. But I’m willing to offer more support.

Here is code that uses the stat() function to pull in a file’s size. It’s only loosely related to this Exercise’s solution.

2023_01_01-Lesson.c

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

int main(int argc, char *argv[])
{
    char *filename;
    struct stat fs;
    int r;
    
    /* check for filename argument */
    if( argc<2 )
    {
        puts("Specify a filename");
        return(1);
    }

    /* operate from the first argument */
    filename = argv[1];

    r = stat(filename,&fs);
    if( r==-1 )
        printf("Unable to read %s\n",filename);
    else
        printf("%s is %lld bytes long\n",filename,fs.st_size);

    return(0);
}

The program checks for a command line argument and fails with an error message if one is missing.

When an argument is present, the stat() function gathers details about the file. If the stat() function returns successfully (the return value r isn’t -1), the file’s size in bytes is output.

Here’s a sample run:

$ ./a.out sonnet18.txt
sonnet18.txt is 636 bytes long

You can read more about the stat() function here. But this challenge is about not using the stat() function. Instead, use some other file manipulation/examination function to determine the file’s length.

As a major hint, it’s possible to use random file access tools to gather how many bytes are in a file.

Ensure that the program reports how many bytes are in the named file, looking like the output shown above. You can view my solution, but only after you try this exercise on your own.

Leave a Reply