C++ File Read Write Example
Following C++ program will read and write a word into a given file.
#include <fstream>#include <iostream>using namespace std;
int main () { char word[20]; //Open a data file to write a word. ofstream fout; fout.open("data.txt");
cout << "Writing a word to data file...\n"; cout << "Enter your word: "; cin.getline(word, 20);
fout << word; // write data fout.close(); // close file
ifstream fin; fin.open("data.txt"); // open file to read
cout << "\nReading a word from a file...\n"; fin >> word; cout << word; //write data to screen fin.close(); //close file return 0;}
Output of Program
#include <fstream>
#include <iostream>
using namespace std;
int main () {
char word[20];
//Open a data file to write a word.
ofstream fout;
fout.open("data.txt");
cout << "Writing a word to data file...\n";
cout << "Enter your word: ";
cin.getline(word, 20);
fout << word; // write data
fout.close(); // close file
ifstream fin;
fin.open("data.txt"); // open file to read
cout << "\nReading a word from a file...\n";
fin >> word;
cout << word; //write data to screen
fin.close(); //close file
return 0;
}
Writing a word to data file...
Enter your word: hello
Reading a word from a file...
hello
Note: Loops can be used to read/write multiple words into a file.