Read and Write Text Files in C++ programming by using fopen() function to read and write any text file by using 'r' to ready file and 'w' to write any text file.
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
void main()
{
FILE *fp;
char ch;
fp = fopen("C://test/My Txt File.txt", "r");
while(1)
{
ch = fgetc(fp);
if(ch == EOF)
break;
cout<<ch;
}
fclose(fp);
getch();
}
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
void main()
{
FILE *fp;
char ch;
int nol = 0, nop = 0, nob = 0, noc = 0;
fp = fopen("C://test/MyTextFile.txt", "r");
while(1)
{
ch = fgetc(fp);
if(ch == EOF)
break;
noc++;
if(ch == ' ')
nob++;
if(ch == '\n')
nol++ ;
if(ch == '\t')
nop++;
}
fclose(fp);
cout<<"Number of characters = "<<noc<<endl;
cout<<"Number of blanks = "<<nob<<endl;
cout<<"Number of tabs = "<<nop<<endl;
cout<<"Number of lines = "<<nol<<endl;
getch();
}
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
void main()
{
FILE *fs, *ft;
char ch; //this is Source File.
cout<<"Starting to read MyTxtFile.txt file"<<endl;
fs = fopen("C://test/MyTxtFile.txt", "r");
if(fs == NULL)
{
cout<<"Cannot open source file"<<endl;
} //this is Target File.
cout<<"Starting to write MyTxtFile.txt file"<<endl;
ft = fopen("C://test/MyTxtFile2.txt", "w");
if(ft == NULL)
{
cout<<"Cannot open target file"<<endl;
fclose(fs);
}
while(1)
{
ch = fgetc(fs);
if(ch == EOF)
break;
else
fputc(ch, ft);
}
fclose(fs);
fclose(ft);
cout<<"Operation success"<<endl;
getch();
}