How to get file information like "ls -la" using C?

I use ar.h to determine the structure. I was wondering how I am going to get information about the file and put it in these specified variables in the structure.

struct ar_hdr { char ar_name[16]; /* name of this member */ char ar_date[12]; /* file mtime */ char ar_uid[6]; /* owner uid; printed as decimal */ char ar_gid[6]; /* owner gid; printed as decimal */ char ar_mode[8]; /* file mode, printed as octal */ char ar_size[10]; /* file size, printed as decimal */ char ar_fmag[2]; /* should contain ARFMAG */ }; 

Using the structure described above, how would I put information from a file from ls -la

-rw-rw----. 1 clean-unix upg40883 368 Oct 29 15:17 testar

?

+4
source share
3 answers

You are looking for stat(2,3p) .

+8
source

To emulate the behavior of ls -la , you need a combination of readdir and stat . Do man 3 readdir and man 2 stat to get information on how to use them.

Capturing ls -la output is possible, but not such a good idea. People can expect a shell script, but not for C or C ++. This is not even what you need to do in Python or perl if you can help it.

You will need to independently build your structure from the data available to you. strftime can be used to format time in a way that you like.

+1
source

To collect data about one file in the archive header record, the main response is stat() ; in other contexts (e.g. ls -la ) you may also need to use lstat() and readlink() . (Beware: readlink() doesn't matter null terminates its returned string!)

With ls -la you are likely to use the opendir() ( readdir() and closedir() ) family of functions to read the contents of a directory.

If you need to handle a recursive search, you will look for nftw() . (There's also less capable ftw() , but you probably would be better off using nftw() .)

0
source

All Articles