You basically have three options.
Option I
Redirect stdin
/stdout
(those are the streams scanf
reads from and printf
writes to) in the console, when you start your program. On both Windows and Linux, this can be done like so:
< in.txt
– redirects all reads fromstdin
toin.txt
> out.txt
– redirects all writes tostdout
toout.txt
You can combine these. For example, to have your program read from in.txt
and write to out.txt
, do this in the terminal (command line):myprogram < in.txt > out.txt
Option 2
Again, you can redirect the standard streams, this time in your code, using freopen
. For example:
freopen("out.txt", "w", stdout);
freopen("in.txt", "r", stdin);
The result will be exactly the same as above.
Option 3
Use C’s file I/O: first fopen
, then fscanf
and fprintf
:
FILE* fIn, fOut;
fIn = fopen("in.txt", "r");
fOut = fopen("out.txt", "w");
// Here you should check if any of them returned NULL and act accordingly
You can then read and write like so:
fscanf(fIn, "%d %d", &x, &y);
fprintf(fOut, "Some result: %d\n", result);
1
solved How to read and write files using printf and scanf in C? [closed]