Search code examples
cstat

Reproducing Linux stat command in C


I'm writing my own version of the stat command and I am having difficulty getting the correct output for the Device field.

When I run the Linux stat command on an empty file in the working directory I get:

Device: 801h/2049d  

To replicate this I tried to extract from the stat structure, the st_dev field.

But printing st_dev gives me

Device: 801

I am missing the h at the end and I am not sure where the 2049d comes from.

Is the first part just a formatting problem? I am printing in hex format. And how can I extract 2049d?


Solution

  • Since (hexadecimal) 0x801 == 2049 (decimal), you can get the output you're after from:

    printf("Device: %xh/%dd\n", st.st_dev, st.st_dev);
    

    The h in the format is the h that appears at the end of 801h; the %x means 'print number in hex'. Similarly, the %d means print in decimal, and the trailing d is the d in 2049d.

    Incidentally, on Linux and other POSIX platforms, you can also avoid repeating the st.st_dev argument. For example:

    #include <stdio.h>
    
    int main(void)
    {
        printf("Device: %1$xh/%1$dd\n", 0x801);
        return 0;
    }
    

    This also produces:

    Device: 801h/2049d
    

    To see why, read the printf() specification very carefully. Note that if you use one of the 1$ modifiers, you must (should) use it with every conversion specification.