Read a String Character by Character from File
Use of fgetc(),feof(),EOF and putchar()
1. Example to read a String using fgetc() and feof() from a file:
#include<stdio.h>
void main()
{
char ch;
FILE *fptr;
fptr=fopen("compuhelp.txt","r");
if(fptr==NULL)
{
printf("\n File could not be opened ");
}
else
{
while(!feof(fptr))
{
ch=fgetc(fptr);
printf("%c",ch);
}
}
fclose(fptr);
}
Output:
This is c file handling.
2. Example to read a String from a file and use of putchar() and EOF:
#include<stdio.h>
void main()
{
char ch;
FILE *fptr;
fptr=fopen("compuhelp.txt","r");
if(fptr==NULL)
{
printf("\n File could not be opened ");
}
else
{
while((ch=fgetc(fptr))!=EOF)
{
putchar(ch);
}
}
fclose(fptr);
}
Output:
This is c file handling.