Read and Write Text File in C

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.

Program Reading Text from Text File

Program

#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();
}
Output
This is test text from MyTxtFile.txt file

Program Count Chars, Spaces, Tabs and NewLines in a Text File

Program

#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();
}
Output
Number of characters = 41
Number of blanks = 6
Number of tabs = 0
Number of lines = 0

Program Copying Text from One to Another Text File

Program

#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();
}
Output
Starting to read MyTxtFile.txt file
Starting to write MyTxtFile.txt file
Operation success