Write a program to write and read a text in/from a file. code example

Example 1: c program to read and write to a file

/*Program to read from file using getc() function*/
#include <stdio.h>
int main() {
 FILE *fp;
 char ch;
 /*Open file in read mode*/
 fp= fopen ('example.txt', 'r');
 while( (ch = getc(fp)) != EOF) {
  /*getc() function reads a character and its value is stored in variable 'ch' until EOF is encountered*/
  printf('%ch', ch);
 }
  fclose(fp);
  return 0;
}

Example 2: Write a program to write content into text file.

//C++ program to write and read text in/from file.
#include <iostream>
#include <fstream>
 
using namespace std;
 
int main()
{
   fstream file; //object of fstream class
    
   //opening file "sample.txt" in out(write) mode
   file.open("sample.txt",ios::out);
    
   if(!file)
   {
       cout<<"Error in creating file!!!"<<endl;
       return 0;
   }
    
   cout<<"File created successfully."<<endl;
   //write text into file
   file<<"ABCD.";
   //closing the file
   file.close();
    
   //again open file in read mode
   file.open("sample.txt",ios::in);
    
   if(!file)
   {
       cout<<"Error in opening file!!!"<<endl;
       return 0;
   }   
    
   //read untill end of file is not found.
   char ch; //to read single character
   cout<<"File content: ";
    
   while(!file.eof())
   {
       file>>ch; //read single character from file
       cout<<ch;
   }
    
   file.close(); //close file
    
   return 0;
}

Tags:

Cpp Example