The ones who are crazy enough to think they can change the world are the ones who do.
- Steve Jobs

C File Read

The following functions are used to read data from the files.

  • fscanf()
  • fgetc()
  • fgets()

Files - fscanf()

The fscanf() function is used to read the sequence of characters, integers, floats, etc. from a file by using appropriate format specifier of data type.

C program - fscanf()

Lets try to code using fscanf() and have some fun.

fscanf.c
#include <stdio.h>
int main()
{
FILE *fptr;     //File pointer declaration
char name[40], name1[40];
fptr = fopen("record.txt", "r+");     //the function fopen opens the record text file
printf("\nEnter your name : ");
scanf("%s", name);
fputs(name,fptr);    //the entered name is written in to the file
rewind(fptr);    //returns pointer to the starting point of the file
fscanf(fptr, "%s ", name1);    //reads the name from file
printf("Name reads from File : %s", name1);
fclose(fptr);     //the function closes the opened file
return 0;
}
  • Enter your name : John
  • Name reads from File : John

Note:

The rewind function resets the pointer to the starting point of a file.

Files - fgetc()

The fgetc() function used to read a single character from a file. It can read only one character at a time.

C program - fgetc()

Lets try to code using fgetc() and have some fun.

fgetc.c
#include <stdio.h>
int main()
{
FILE *fptr;     //File pointer declaration
char name[40], ch;
fptr = fopen("record.txt", "r+");     //the function fopen opens the record text file
printf("\nEnter your Name : ");
scanf("%s", name);
fputs(name, fptr);
rewind(fptr);
printf("Name : ");
while((ch=fgetc(fptr))!=EOF)     //the fgetc function reads a character from the file
{
putchar(ch);
}
fclose(fptr);     //the function closes the opened file
return 0;
}
  • Enter your Name : Jiju
  • Name : Jiju

Note:

The program illustrates that the fgetc function reads the character one by one and print the character one by one using putchar function.

Files - fgets()

The fgets() function used to read a string from a file.

C program - fgets()

Lets try to code using fgets() and have some fun.

fgets.c
#include <stdio.h>
int main()
{
FILE *fptr;     //File pointer declaration
char name[40];
fptr = fopen("record.txt", "w");     //the function fopen opens the record text file
printf("\nEnter your name : ");
scanf("%s", name);
fputs(name, fptr);
rewind(fptr);
fgets (name1, 40, fptr );    //reads the string from the file
prinf("Name : %s", name);
fclose(fptr);     //the function closes the opened file
return 0;
}
  • Enter your name : Jiju
  • Name : Jiju

Note:

From the above program the fgets() function reads a string from a file record.txt. The integer parameter inside the fgets function is the total number of characters that the user wants to read from a file.

Report Us

We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.

Report