Sunday, July 30, 2017

C++ program to write a word into a file.

File Management in C++

C++ program to write a word into a 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);

   // write data into the file.
   fout << word;
   fout.close();

   ifstream fin;    //open file to read.
   fin.open("data.txt"); 
   cout << "\nReading a word from a file...\n"; 
   fin >> word; 
   cout << word;    //write data to screen.
   
   fin.close();     //close the opened file.
   return 0;
}

Output of program

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.

1 comment: