Jimmy Suh
Jimmy Suh

Reputation: 212

Reading from stdin after reading from file

I am trying to read each line from stdin after I finished reading from given file, or if given file name does not exist. Currently I am using below format.

while (fgets(buf, sizeof(buf), fp)!=NULL){
  main process...
}
while (fgets(buf, sizeof(buf), stdin)!=NULL){
  main process...
}

This format does work as I intended. However, main process is quite a chunky code, and would there be a way to shorten this, so that I can write while loop only once? Thank you.

Upvotes: 0

Views: 65

Answers (2)

user10678532
user10678532

Reputation:

would there be a way to shorten this, so that I can write while loop only once?

There isn't.

You can of course abstract the code into a function which takes a FILE* as a parameter, or extend the stdio interfaces yourself (example), but the long and short of it is that neither standard C nor any popular libc implementation have anything like the ARGV file handle from perl, or anything that let you open a list of files as a single stream.

Upvotes: 1

slingeraap
slingeraap

Reputation: 578

If your problem is that 'main process' consists of a lot of lines of code that you do not want to duplicate, the most straightforward solution is to make a function that implements main process.

Since the while loops are identical, save for the file pointer, you could also include the while loop in the function, with the file pointer as a parameter (as in David's remark).

Then you should add a function like this:

void process_input(FILE *input_handle) {
   char buf[1024];
   while (fgets(buf, sizeof(buf), input_handle) != NULL) {
      main process...
   }
}

And your original code then should be replaced with:

process_input(fp);
process_input(stdin);

Upvotes: 3

Related Questions