Files - InputSo far all input data is entered through the keyboard.When there is a lot of data, it is easier to save the data in a file and make the program read or input the data from the file. To read from the file, we need to open the file before we start to read and close the file after reading all the data.2
Files - OutputInstead of displaying the results of the program on the screen, we can write to a file.For example, the program can produce a report that is written to the file instead of the screen.To write data to a file, we need to open the file before we start to write and close the file after we finish writing.3
Input/ Output StreamsA stream is a flow of characters (or other kind of data). If the flow is into the program, the stream is called an input stream. If the flow is out of the program, the stream is called an output stream. The input stream can flow from the keyboard or from the file. Similarly, an output stream can go to the screen or to a file.4
Input/ Output Streamscin is an input stream connected to the keyboard.cout is an output stream connected to the screen.To read input from a file, the program must connect the file to a (stream) object of the class ifstream.To send output to a file, the program must connect the file to a (stream) object of the class ofstream.The classes ifstream and ofstream are defined in the <fstream> library and placed in the std namespace.5
Opening a FileBefore we can open a file, we need to declare an input/output stream for a file:Input stream : ifstream in_file;Output stream:ofstream out_file;To connect a stream to a file named mydata.txt:out_file.open("mydata.txt");Combine the 2 statements above to form the statement below:ofstream out_file("mydata.txt", ios::out);file modefile name6
File ModeModeMeaningios::in Open text file in read mode to allow reading from the file.