we are using the iostream standard library, it provides cin and cout methods for reading from input and writing to output respectively.
हम iostream लाइब्रेरी के मैथड cin और cout क्रमशः इनपुट लेखे व आउपुअ डिस्पले करने के लिए यूज आते है।
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:
इसी प्रकार किसी फाइल में डाटा लिखने एवं पढने के लिए fstream लाइब्रेरी के मैथडस उपयोग में आते हैं।
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. यह फाइल बनाने एवं इन्फोरमेशन को उस फाइल में लिखने के लिए प्रयोग किया जाता है। |
writing to a file
#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.
Reading from a file
#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;
}
Output:
Welcome to javaTpoint.
C++ Tutorial
C++ Read and Write Example
#include <fstream>
#include <iostream>
using namespace std;
int main () {
char input[75];
ofstream os;
os.open("testout.txt");
cout <<"Writing to a text file:" << endl;
cout << "Please Enter your name: ";
cin.getline(input, 100);
os << input << endl;
cout << "Please Enter your age: ";
cin >> input;
cin.ignore();
os << input << endl;
os.close();
ifstream is;
string line;
is.open("testout.txt");
cout << "Reading from a text file:" << endl;
while (getline (is,line))
{
cout << line << endl;
}
is.close();
return 0;
}
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
No comments:
Post a Comment