Node:Internal File Description, Next:Internal File Ops, Previous:Sample Library, Up:Sample Library
chdir and statThis 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:
"name"
stat'ed.
"dev"
"ino"
"mode"
"nlink"
"uid"
"gid"
"size"
"blocks"
"atime"
"mtime"
"ctime"
strftime
(see Built-in Functions).
"pmode"
ls -l--for example, "drwxr-xr-x".
"type"
"blockdev"
"chardev"
"directory"
"fifo"
"file"
"socket"
AF_UNIX ("Unix domain") socket in the
filesystem.
"symlink"
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):
"blksize"
stat structure.
"linkval"
"rdev"
"major"
"minor"