0

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; } 
2
  • 2
    for(int i=2; i<argc; i++) { fname = argv[i]; ... } Commented Mar 20, 2013 at 3:07
  • I need to just be able to open multiple file arguments. So every file argument at argv2 argv3 argv4........ Open each of those files Commented Mar 20, 2013 at 14:16

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.