In C++ programming we’re utilizing the iostream normal library, it supplies cin and cout strategies for studying from enter and writing to output respectively.
To learn and write from a file we’re utilizing the usual C++ library referred to as fstream. Allow us to see the information sorts outline in fstream library is:
Knowledge Sort | Description |
---|---|
fstream | It’s used to create recordsdata, write information to recordsdata, and browse information from recordsdata. |
ifstream | It’s used to learn information from recordsdata. |
ofstream | It’s used to create recordsdata and write information to the recordsdata. |
C++ FileStream instance: writing to a file
Let’s see the easy instance of writing to a textual content file testout.txt utilizing C++ FileStream programming.
1 |
#embody <iostream>#embody <fstream>utilizing namespace std;int principal () { ofstream filestream("testout.txt"); if (filestream.is_open()) {filestream << "Welcome to javaTpoint.n";filestream << "C++ Tutorial.n";filestream.shut(); } else cout <<"File opening is fail."; return 0;}</fstream></iostream> |
Output:
1 |
The content material of a textual content file <strong>testout.txt</strong> is about with the information:Welcome to javaTpoint.C++ Tutorial. |
C++ FileStream instance: studying from a file
Let’s see the easy instance of studying from a textual content file testout.txt utilizing C++ FileStream programming.
1 |
#embody <iostream>#embody <fstream>utilizing namespace std;int principal () { string srg; ifstream filestream("testout.txt"); if (filestream.is_open()) {whereas ( getline (filestream,srg) ){ cout << srg <<endl;}filestream.shut(); }="" else="" {="" cout="" <<="" "file="" opening="" is=""></endl;}filestream.close();><endl; }="" return=""></endl;></fstream></iostream> |
Be aware: Earlier than operating the code a textual content file named as “testout.txt” is should be created and the content material of a textual content file is given under:
Welcome to javaTpoint.
C++ Tutorial.
Output:
1 |
Welcome to javaTpoint.C++ Tutorial. |
C++ Learn and Write Instance
Let’s see the easy instance of writing the information to a textual content file testout.txt after which studying the information from the file utilizing C++ FileStream programming.
1 |
#embody <fstream>#embody <iostream>utilizing namespace std;int principal () { char enter[75]; ofstream os; os.open("testout.txt"); cout <<"Writing to a textual content file:" << endl; cout << "Please Enter your title: ";cin.getline(enter, 100); os << enter << endl; cout << "Please Enter your age: ";cin >> enter; cin.ignore(); os << enter << endl; os.shut(); ifstream is;string line; is.open("testout.txt");cout << "Studying from a textual content file:" << endl;whereas (getline (is,line)) { cout << line << endl; } is.shut(); return 0;}</iostream></fstream> |
Output:
1 |
Writing to a textual content file: Please Enter your title: Nakul JainPlease Enter your age: 22 Studying from a textual content file: Nakul Jain 22 |