Node:Internal File Description, Next:, Previous:Sample Library, Up:Sample Library

Using chdir and stat

This section shows how to use the new functions at the awk level once they've been integrated into the running gawk interpreter. Using chdir is very straightforward. It takes one argument, the new directory to change to:

newdir = "/home/arnold/funstuff"
ret = chdir(newdir)
if (ret < 0) {
    printf("could not change to %s: %s\n",
                   newdir, ERRNO) > "/dev/stderr"
    exit 1

The return value is negative if the chdir failed, and ERRNO (see Built-in Variables) is set to a string indicating the error.

Using stat is a bit more complicated. The C stat function fills in a structure that has a fair amount of information. The right way to model this in awk is to fill in an associative array with the appropriate information:

file = "/home/arnold/.profile"
fdata[1] = "x"    # force `fdata' to be an array
ret = stat(file, fdata)
if (ret < 0) {
    printf("could not stat %s: %s\n",
             file, ERRNO) > "/dev/stderr"
    exit 1
printf("size of %s is %d bytes\n", file, fdata["size"])

The stat function always clears the data array, even if the stat fails. It fills in the following elements:

The name of the file that was stat'ed.
The file's device and inode numbers, respectively.
The file's mode, as a numeric value. This includes both the file's type and its permissions.
The number of hard links (directory entries) the file has.
The numeric user and group ID numbers of the file's owner.
The size in bytes of the file.
The number of disk blocks the file actually occupies. This may not be a function of the file's size if the file has holes.
The file's last access, modification, and inode update times, respectively. These are numeric timestamps, suitable for formatting with strftime (see Built-in Functions).
The file's "printable mode." This is a string representation of the file's type and permissions, such as what is produced by ls -l--for example, "drwxr-xr-x".
A printable string representation of the file's type. The value is one of the following:
The file is a block or character device ("special file").
The file is a directory.
The file is a named-pipe (also known as a FIFO).
The file is just a regular file.
The file is an AF_UNIX ("Unix domain") socket in the filesystem.
The file is a symbolic link.

Several additional elements may be present depending upon the operating system and the type of the file. You can test for them in your awk program by using the in operator (see Referring to an Array Element):

The preferred block size for I/O to the file. This field is not present on all POSIX-like systems in the C stat structure.
If the file is a symbolic link, this element is the name of the file the link points to (i.e., the value of the link).
If the file is a block or character device file, then these values represent the numeric device number and the major and minor components of that number, respectively.