I am using ar.h for the defining the struct. I was wondering on how I would go about getting information about a file and putting it into those specified variables in the struct.
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 struct defined above, how would I put get the information from the file from ls -la
-rw-rw----. 1 clean-unix upg40883 368 Oct 29 15:17 testar
?
You're looking for stat(2,3p)
.
In order to emulate the behavior of ls -la
you need a combination of readdir
and stat
. Do a man 3 readdir
and a man 2 stat
to get information on how to use them.
Capturing the output of ls -la
is possible, but not such a good idea. People might expect that of a shell script, but not a C or C++ program. It's even sort of the wrong thing to do in Python or perl if you can help it.
You will have to construct your structure yourself from the data available to you. strftime
can be used for formatting the time in a manner you like.
For collecting data about a single file into an archive header entry, the primary answer is stat()
; in other contexts (such as ls -la
), you might also need to use lstat()
and readlink()
. (Beware: readlink()
does not null terminate its return string!)
With ls -la
, you would probably use the opendir()
family of functions (readdir()
and closedir()
too) to read the contents of a directory.
If you needed to handle a recursive search, then you'd be looking at nftw()
. (There's also a less capable ftw()
, but you'd probably be better off using nftw()
.)