Using Struct Stat()

For another project, I've whipped up a little function that does something similiar to what you need. Take a look at sprintstatf.

Here's an example of usage:

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

#include "sprintstatf.h"

int
main(int argc, char *argv[])
{
    char *outbuf = (char *)malloc(2048 * sizeof(char));
    struct stat stbuf;
    char *fmt = \
        "st_atime (decimal) = \"%a\"\n"
        "st_atime (string)  = \"%A\"\n"
        "st_ctime (decimal) = \"%c\"\n"
        "st_ctime (string)  = \"%C\"\n"
        "st_gid   (decimal) = \"%g\"\n"
        "st_gid   (string)  = \"%G\"\n"
        "st_ino             = \"%i\"\n"
        "st_mtime (decimal) = \"%m\"\n"
        "st_mtime (string)  = \"%M\"\n"
        "st_nlink           = \"%n\"\n"
        "st_mode  (octal)   = \"%p\"\n"
        "st_mode  (string)  = \"%P\"\n"
        "st_size            = \"%s\"\n"
        "st_uid             = \"%u\"\n"
        "st_uid             = \"%U\"\n";

    lstat(argv[1], &stbuf);

    sprintstatf(outbuf, fmt, &stbuf);
    printf("%s", outbuf);

    free(outbuf);
    exit(EXIT_SUCCESS);
}

/* EOF */

Yes, buf is being used here as an out-parameter. The results are stored in buf and the return value of stat is an error code indicating if the stat operation succeeded or failed.

It is done this way because stat is a POSIX function, designed for C, which does not support out-of-band error reporting mechanisms like exceptions. If stat returned a struct, then it would have no way to indicate errors. Using this out-parameter method also allows the caller to choose where they want to store the results, but that's a secondary feature. It's perfectly fine to pass the address of a normal local variable, just like you have done here.

You access the fields of a struct like you would any other object. I presume you are at least familar with object notation? E.g. the st_dev field within the stat struct called buf is accessed by buf.st_dev. So:

cout << buf.st_dev << endl;

etc.

Tags:

C++

Struct

Posix