C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
C++ Files and StreamsIn 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:
C++ FileStream example: writing to a fileLet's see the simple example of writing to a text file testout.txt using C++ FileStream programming. #include <iostream> #include <fstream> using namespace std; int main () { ofstream filestream("testout.txt"); if (filestream.is_open()) { filestream << "Welcome to javaTpoint.\n"; filestream << "C++ Tutorial.\n"; filestream.close(); } else cout <<"File opening is fail."; return 0; } Output: The content of a text file testout.txt is set with the data: Welcome to javaTpoint. C++ Tutorial. C++ FileStream example: reading from a fileLet's see the simple example of reading from a text file testout.txt using C++ FileStream programming. #include <iostream> #include <fstream> using namespace std; int main () { string srg; ifstream filestream("testout.txt"); if (filestream.is_open()) { while ( getline (filestream,srg) ) { cout << srg <<endl; } filestream.close(); } else { cout << "File opening is fail."<<endl; } return 0; } 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:
|