104
Note: Before running the code a text file named as “testout.txt” is need to be created and the content of a text file is given below:
C++ Files and Streams
In C++ programming we are using the iostream standard library, it provides cin and cout methods for reading from input and writing to output respectively.
To read and write from a file we are using the standard C++ library called fstream. Let us see the data types define in fstream library is:
Data Type | Description |
---|---|
fstream | It is used to create files, write information to files, and read information from files. |
ifstream | It is used to read information from files. |
ofstream | It is used to create files and write information to the files. |
C++ FileStream example: writing to a file
Let’s see the simple example of writing to a text file testout.txt using C++ FileStream programming.
Output:
The content of a text file testout.txt is set with the data: Welcome to Tutor Aspire. C++ Tutorial.
C++ FileStream example: reading from a file
Let’s see the simple example of reading from a text file testout.txt using C++ FileStream programming.
Note: Before running the code a text file named as “testout.txt” is need to be created and the content of a text file is given below:
Welcome to Tutor Aspire.
C++ Tutorial.
Output:
Welcome to Tutor Aspire. C++ Tutorial.
C++ Read and Write Example
Let’s see the simple example of writing the data to a text file testout.txt and then reading the data from the file using C++ FileStream programming.
Output:
Writing to a text file: Please Enter your name: Nakul Jain Please Enter your age: 22 Reading from a text file: Nakul Jain 22
Next TopicC++ getline()