I'm trying to figure out how exactly to use stat() to capture information about a file. What I need is to be able to print several fields of information about a file. So..
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
using namespace std;
int main() {
struct stat buf;
stat("file",&buf);
...
cout << st_dev << endl;
cout << st_ino << endl;
cout << st_mode << endl;
cout << st_nlink << endl;
cout << st_uid << endl;
cout << st_gid << endl;
cout << st_rdev << endl;
cout << st_size << endl;
cout << st_blksize << endl;
cout << st_blocks << endl;
cout << st_atime << endl;
cout << st_mtime << endl;
cout << st_ctime << endl;
...
}
I'm thoroughly confused about how to do this. Why is &buf a parameter to stat? I don't care about storing this information in memory, I just need the outputted fields within my c++ program. How do I access the information contained in the struct? Is buf actually supposed to contain the returned information from stat()?
struct stat is a system struct that is defined to store information about files. It is used in several system calls, including fstat, lstat, and stat.
The stat() function gets status information about a specified file and places it in the area of memory pointed to by the buf argument. If the named file is a symbolic link, stat() resolves the symbolic link. It also returns information about the resulting file.
The stat structure is returned by the fstat() and stat() functions. It provides detailed information about a file. The information returned depends on the type of file and/or the file system on which the file resides.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With