Read Integers from File in C File Handling
Read Data from File in C File Handling
Read Mode
ii) Read Mode: This mode is used to open the file in read mode if file already exists and this mode is denoted by ‘r’. If the file does not exists, the compiler returns NULL to the file pointer.
FILE *fptr; // declaration of file pointer
fptr= fopen(“FILE_NAME”,”r”); //opening a file in read mode only
Example to read two numbers from a file:
#include<stdio.h>
void main()
{
int num1,num2;
FILE *fptr;
fptr=fopen("compuhelp.txt","r");
if(fptr==NULL)
{
printf("\n File could not be opened ");
}
else
{
fscanf(fptr,"%d%d",&num1,&num2);
}
printf("\n First value is %d",num1);
printf("\n Second value is %d",num2);
fclose(fptr);
}
Output:
First value is 100
Second value is 200
Now you can see the output the two integer values which we read from the following notepad file named as compuhelp.txt by using the read mode in the code.