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<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
fp = fopen("C://test/MyTxtFile.txt", "r");
while(1)
{
ch = fgetc(fp);
if(ch == EOF)
break;
printf("%c", ch);
}
fclose(fp);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
int nol = 0, not = 0, nob = 0, noc = 0;
fp = fopen("C://test/MyTxtFile.txt", "r");
while(1)
{
ch = fgetc(fp);
if(ch == EOF)
break;
noc++;
if(ch == ' ')
nob++;
if(ch == '\n')
nol++;
if(ch == '\t')
not++;
}
fclose(fp);
printf("Number of characters = %d\n", noc);
printf("Number of blanks = %d\n", nob);
printf("Number of tabs = %d\n", not);
printf("Number of lines = %d", nol);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fs, *ft;
char ch; //this is Source File.
puts("Starting to read MyTxtFile.txt file");
fs = fopen("C://test/MyTxtFile.txt", "r");
if(fs == NULL)
{
puts("Cannot open source file");
} //this is Target File.
puts("Starting to write MyTxtFile.txt file");
ft = fopen("C://test/MyTxtFile2.txt", "w");
if(ft == NULL)
{
puts("Cannot open target file");
fclose(fs);
}
while(1)
{
ch = fgetc(fs);
if(ch == EOF)
break;
else
fputc(ch, ft);
}
fclose(fs);
fclose(ft);
puts("Operation success");
getch();
}