-   Programming (
-   -   How does passing argument to main work (

Linh 06-26-2003 04:11 PM

How does passing argument to main work
I got this code from a book. It said "The implementation of waitfile uses fstat to extract the time when the file was last changed".

1) The program has two argument in main as in
main(argc, argv).
Do I included these value at the command line when I
run the program as in ./waitfile prog1 a

2) How do I get this program to run ?

3) How does main(argc, argv) work ?

4) root:~# ./waitfile
./waitfile: 3: Unknown error 3221225157

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>

char *progname;

main(argc, argv)
int argc;
char *argv[];

int fd;
struct stat stbuf;
time_t old_time = 0;

progname = argv[0];
if (argc < 2)
error ("Usage: %s filename [cmd]", progname);
if ((fd = open(argv[1], 0)) == -1)
error ("can 't open %s", argv[1]);
fstat(fd, &stbuf);
while (stbuf.st_mtime != old_time)
old_time = stbuf.st_mtime;
fstat(fd, &stbuf);

if (argc == 2)
execlp("cat", "cat", argv[1], (char *) 0);
error ("can 't execute cat %s", argv[1]);
execvp(argv[2], &argv[2]);
error ("can 't execute %s", argv[2]);

Palin 06-26-2003 04:30 PM

here is how those two arguments act when passed to main.
the first is the number of arguments passed to the command line
the second is an array of strings containing the arguments. It looks like this program expects atleast a filename.

Linh 06-26-2003 04:44 PM

How would you run the program ? Please specify it

Is it as shown below ?
ex: ./waitfile program1 second-argument

1) What is the second-argument ?
2) What should the second-argument contain ?

Palin 06-26-2003 05:04 PM

I don't believe this program requires a second argument.
./waitfile <filename>

Hko 06-27-2003 11:12 AM



main(argc, argv)
int argc;
char *argv[];

That's an old book, ins't it?

Linh 06-27-2003 01:08 PM

The name of the book is
The name of the book is
The UNIX Programming Environment
by Brian W. Kernighan and Rob Pike
published in 1984

the program is on page 221

If that is the old code, then what is its new counterpart ?

All times are GMT -5. The time now is 11:06 AM.