tags:

views:

216

answers:

1

stattest.c:

// compile: gcc -o stattest stattest.c
#include <stdio.h>
#include <sys/stat.h>

int main(int argc, char *argv[]) {
    struct stat stats;
    stat(argv[1], &stats);
    printf("%lli\n", (long long)stats.st_dev);
    return 0;
}

Usage:

stat -f "%r" /dev/disk0
=> 234881024                  (Value that I'm looking for.)

./teststat /dev/disk0
=>  44921876

python -c 'import os,sys; print os.stat(sys.argv[1]).st_dev' /dev/disk0
=>  44921876

Why doesn't my code give me the value the stat command gives me?

Update 1

Extracting the major number of 44921876 gives me 2 which is /dev/tty.

Update 2

Specifying a file on the filesystem works. (I'm only using python here because it's faster.)

python -c "import sys,os; print os.stat(sys.argv[1]).st_dev" /path/to/file
=> 234881024
+3  A: 

Try printing the st_rdev member. The manual page says:

struct stat {
   dev_t    st_dev;    /* device inode resides on */
   [ ... snip ... ]
   dev_t    st_rdev;   /* device type, for special file inode */
};

I think you're not printing the same field that the %r formatter accesses. You're not interested in the device the device file is on, but the device that the file describes.

The numbers are at least consistent with your ls output; major=14 and minor=0, and you print 234881024, which in hex is 0xE000000. 0xE is, of course, 14 decimal. This indicates Mac OS X stores the major number in the top 8 bits, and the minor number in the lower 24. This, in turn, implies that the dev_t type is 32-bit, which makes your printing it as long long a bit dubious.

unwind
The `long long` is only there in case `dev_t` switches to 64bit.
Georg
Thanks a lot! Works perfectly.
Georg