Read a String(fgetc() and fgets() function's)
Read a Character from a File in C File Handling
Program to read a character from the file in C file handling by using fgetc().
1. Example to read a character using fgetc() 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
{
ch=fgetc(fptr);
}
printf("\n Character is %c",ch);
fclose(fptr);
}
Output:
Character is T
2. Example to read a String using fgets() from a file:
#include<stdio.h>
void main()
{
char str[80];
FILE *fptr;
fptr=fopen("compuhelp.txt","r");
if(fptr==NULL)
{
printf("\n File could not be opened ");
}
else
{
fgets(str,60,fptr);
}
printf("\n String is %s",str);
fclose(fptr);
}
Output:
String is This is c file handling.Here is the use of fputs().