21.07.2015 Views

GAWK: Effective AWK Programming

GAWK: Effective AWK Programming

GAWK: Effective AWK Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

294 <strong>G<strong>AWK</strong></strong>: <strong>Effective</strong> <strong>AWK</strong> <strong>Programming</strong>#include "awk.h"#include /* do_chdir --- provide dynamically loadedchdir() builtin for gawk */static NODE *do_chdir(tree)NODE *tree;{NODE *newdir;int ret = -1;if (do_lint && get_curfunc_arg_count() != 1)lintwarn("chdir: called with incorrect number of arguments");newdir = get_scalar_argument(tree, 0);The file includes the "awk.h" header file for definitions for the gawk internals. It includes for access to the major and minor macros.By convention, for an awk function foo, the function that implements it is called ‘do_foo’.The function should take a ‘NODE *’ argument, usually called tree, that represents theargument list to the function. The newdir variable represents the new directory to changeto, retrieved with get_argument. Note that the first argument is numbered zero.This code actually accomplishes the chdir. It first forces the argument to be a stringand passes the string value to the chdir system call. If the chdir fails, ERRNO is updated.The result of force_string has to be freed with free_temp:(void) force_string(newdir);ret = chdir(newdir->stptr);if (ret < 0)update_ERRNO();free_temp(newdir);Finally, the function returns the return value to the awk level, using set_value. Then itmust return a value from the call to the new built-in (this value ignored by the interpreter):}/* Set the return value */set_value(tmp_number((<strong>AWK</strong>NUM) ret));/* Just to make the interpreter happy */return tmp_number((<strong>AWK</strong>NUM) 0);The stat built-in is more involved. First comes a function that turns a numeric modeinto a printable representation (e.g., 644 becomes ‘-rw-r--r--’). This is omitted here forbrevity:/* format_mode --- turn a stat mode fieldinto something readable */

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!