Reputation: 3
What my main is supposed to do is either read from stdin using system calls. Or if file arguments are given open the file arguments. I had already coded this to read from one file argument. But now I need it to open from multiple file arguments and I am short on the logic as to how to do this. How would I get my code to be able to open multiple file arguments?
int main(int argc, char *argv[]) {
char *file_pathname = NULL;
int fd;
char file_buffer[540];
//Check for proper number of arguments:
if(argc < 2) {
exit(2);
}
if(argc < 3) {
file_pathname = "stdin";
}
file_pathname = argv[2];
if(argc < 3) {
((fd = read(STDIN_FILENO,file_buffer, FILE_BUFFER_SIZE)));
}
// FILE argument given, so try to open it:
if (argc == 3) {
if ((fd = open(file_pathname,O_RDONLY)) == -1) {
perror("ERROR OPENING FILE");
return 2;
}
Upvotes: 0
Views: 2043
Reputation: 16441
Start with a function that gets a file descritor and does what you want:
void do_stuff(int fd);
Add another one, which does the same with a file name:
void do_stuff_fname(const char *fname); /* Open fname and call do_stuff */
Now, your main
should call either:
if (argc < 2) {
do_stuff(STDIN_FILENO);
} else {
int i;
for (i=1; i<argc; i++) do_stuff_fname(argv[i]);
}
You can improve this by using getopt
, as JustAnotherCurious suggested
Upvotes: 0
Reputation: 2240
If you want your program run only on linux (POSIX Compatible) system you can be interested in
man 3 getopt
This is function that can help you to parse command line arguments in short unix style, for example:
myprog -a 5654 -f -n ~/Test/input.txt
There are also getopt_long() and getopt_long_only() if you want to parse long options.
If you want some specific argument parser(which i do NOT recommend), you can implement it as library.
There are glib parser if you are using glib or gtk. Or a parser in qxt (an extension Qt library) if you have a qt project. Or you can just google for more lightweight cross-platform argument parsers if you need.
Upvotes: 1