V
Standard I/O Streams
Command line redirect
>
<
on UNIX |
For example to send the output from your application to a file, you would
do:
application.exe > output.txt
To get data from a file you would do:
application.exe < input.txt
To redirect both you input and output you would do:
application.exe < input.txt > output.txt
Benifits
-
Easy to use. Don't have to worry about programming file I/O in your program.
-
Can switch streams without modifying your code.
-
If the output is too long or you can save it for review, you can redirect
stdout to a file.
-
If the data is a lot to enter, you can redirect the data from a prepared
file.
Use cerr to split output and prompts, so that if you are capturing the output,
for example, you can ignore prompts.
cerr and cout by default are the screen. This way if you redirect cout to
a printer, you will be able to have some messages appear on the screen. This
is useful to have prompts appear only on the screen.
File is a collection of data stored on the disk.
-
Input file (data file) contains information that would normally be typed
in.
-
Output file contains information that might have appeared on the screen
as output from your program.
Advantages:
-
Data is typed once
-
Set set of input for a program
-
Good for large sets of data. Also good for passing output of one program
to the input of another.
#include <fstream>
ofstream fout("output.txt");
fout will be a file output stream to the file "output.txt".
ifstream fin("input.txt");
fin will be a file input stream from the file "input.txt".
If you write to the stream, fout, instead of cout, you will write to a file.
fout << "Hello";
Instead of cin, you can get data from a file.
fin >> i;
When you are done with a file stream, you should close it before you exit
the program.
fout.close();
fin.close();
Use NULL to check for errors.
This will allow you to append to the end of a file:
ofstream log("output.log",ios_base::app);
Command line parameters:
main(int argc, char *argv[])
-
argc is the amount of parameters.
-
argv is an array of parameters.
For example to run the command:
addnum 4 5
argc is 3. There are 3 parameters.
-
argv[0] = "addnum"
-
argv[1] = "4"
-
argv[2] = "5"
atoi is used to convert an ascii value to an integer.
For example in the above:
int i;
i=atoi(argv[1]);
i will have the value of 4 stored in it as an integer.