Dynamic file stream handling in C with freopen

306 views Asked by At

I am trying to write a program that ideally accepts arguments that specify both a source file (to read from) and a destination file (to write to).

The program replaces specified characters in source file, with other specified characters, then writes the output to the destination file.

There are 3 special cases I want to handle, though:

  1. Only a source file to read from is provided.

    Desired Behavior: Display the result of replacing the text to the standard output (terminal)

  2. Only a destination file to write to is provided.

    Desired Behavior: Read from standard input, replacing desired letters and writing result to destination file name provided.

  3. Neither the source file nor the destination file are provided.

    Desired Behavior: Read from the standard in, replace characters, write to standard out.

I believe the way to do this is using freopen(), but I cannot wrap my head around the logic of when the file gets opened or how freopen() 3rd argument (stream) works.

What is the traditional way of handling this problem? Is freopen() even the function I am looking for to do this? Or is there some great lesser known function made for situations like these?

Some pseudo code would be really appreciated.

2

There are 2 answers

2
Barmar On

The third argument is which of the standard file streams you want to replace with a file.

So the logic will be something like:

const char *input_file = NULL;
const char *output_file = NULL;

// parse arguments, setting the above variables to the appropriate arguments if supplied

if (input_file) {
    freopen(input_file, "r", stdin);
}

if (output_file) {
    freopen(output_file, "w", stdout);
}

Then the rest of the program uses stdin and stdout normally.

0
the busybee On

The traditional (unixoid) way is to use only stdin and stdout.

If you want to provide an input file, use input redirection:

your_program < input_file

If you want to provide an output file, use output redirection:

your_program > output_file

If you want to provide an input file and an output file, use both ways of redirection:

your_program < input_file > output_file

And you could even add your program to a chain of commands, using pipes:

run_before | your_program | run_after

This gives you a maximum of flexibility.

It is still possible to provide options to your program.