20 Files.pptx - Topic 20 Files 1 Files Input So far all input data is entered through the keyboard When there is a lot of data it is easier to save the

20 Files.pptx - Topic 20 Files 1 Files Input So far all...

This preview shows page 1 - 8 out of 35 pages.

Topic 20 Files 1
Image of page 1
Files - Input So 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
Image of page 2
Files - Output Instead 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
Image of page 3
Input/ Output Streams A 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
Image of page 4
Input/ Output Streams cin 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
Image of page 5
Opening a File Before 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 mode file name 6
Image of page 6
File Mode Mode Meaning ios::in Open text file in read mode to allow reading from the file.
Image of page 7
Image of page 8

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture