Advanced Programming in the UNIX Environment: Second Edition [Electronic resources]

W. Richard Stevens; Stephen A. Rago

نسخه متنی -صفحه : 369/ 125
نمايش فراداده

7.4. Command-Line Arguments

When a program is executed, the process that does the exec can pass command-line arguments to the new program. This is part of the normal operation of the UNIX system shells. We have already seen this in many of the examples from earlier chapters.

Example

The program in Figure 7.4 echoes all its command-line arguments to standard output. Note that the normal echo(1) program doesn't echo the zeroth argument.

If we compile this program and name the executable echoarg, we have

$

./echoarg arg1 TEST foo argv[0]: ./echoarg argv[1]: arg1 argv[2]: TEST argv[3]: foo

We are guaranteed by both ISO C and POSIX.1 that argv[argc] is a null pointer. This lets us alternatively code the argument-processing loop as

for (i = 0; argv[i] != NULL; i++)

Figure 7.4. Echo all command-line arguments to standard output
#include "apue.h" int main(int argc, char *argv[]) { int i; for (i = 0; i < argc; i++) /* echo all command-line args */ printf("argv[%d]: %s\n", i, argv[i]); exit(0); }