Basic Operation on Text File in C++

writing in a text file

#include<fstream.h>
void main()
{
ofstream fout(“abc.txt”);
char string[100]=”The joy that you give to others is the joy that comes back      to you”;
fout<<string;
fout.close();

}

reading from text file character by character and displaying its contents

#include<fstream.h>
#include<conio.h>
void main()
{
ifstream fin(“abc.txt”);
char ch;
while(!fin.eof())
{
fin.get(ch);
cout<<ch;
}
fin.close();
}

reading from text file word by word and displaying its contents

#include<fstream.h>
#include<conio.h>
void main()
{
ifstream fin(“abc.txt”);
char ch[20];
while(!fin.eof())
{
fin.getline(ch,20,’ ‘);   //you can also use  fin>>ch;
cout<<ch;
}
fin.close();
getch();
}

reading from text file line by line and displaying its contents

#include<fstream.h>
#include<conio.h>
void main()
{
ifstream fin(“abc.txt”);
char ch[80];
while(!fin.eof())
{
fin.getline(ch,80,”\n”);
cout<<ch;
}
fin.close();

}

Program to copy contents of file(abc.txt) to file(xyz.txt).

#include<fstream.h>
void main()
{
ifstream fin(“abc.txt”);
ofstream fout(“xyz.txt”);

char ch;
while(!fin.eof())
{
fin.get(ch);
fout<<ch;
}
fin.close();

fout.close();
}

Program to find the size of the file in bytes.

#include<fstream.h>
#include<conio.h>
void  main()
{
ifstream fin(“abc.txt”);
clrscr();
char ch; int count=0;
while(!fin.eof())
{
fin.get(ch);
count++;
}
cout<<“Size of the file is “<<count<<” bytes”;
fin.close();
getch();

}

Program to count number of words starting with capital A

#include<fstream.h>
#include<conio.h>
void main()
{
ifstream fin(“abc.txt”);
char word[30]; int ctr=0;
while(!fin.eof())
{
fin>>word;
          if(word[0]==’A’)
ctr++;
}
cout<<“Number of words starting with A is”<<ctr;
fin.close();
getch();
}

Program to count number of lines in a text file which are palindromes.

#include<fstream.h>
#include<conio.h>
void main()
{
ifstream fin;
fin.open(“out.txt”);
char line[80], line2[80]; int count=0;
while(!fin.eof())
{
fin.getline(line,80,’\n’);
          strcpy(line2,line);
           strrev(line2);
           if(strcmpi(line, line2)==0))
                    count++;
     }
cout<<“Number of palindromes in the file is “<<count;
fin.close();
getch();

}

Leave a Reply

Your email address will not be published. Required fields are marked *