Reading File in C
1. Reading text files in C
Below is the C program to read the contents from the file:
// C program to read contents
// from the file
#include <stdio.h>
#include <stdlib.h>
// Driver code
int main()
{
char str[80];
FILE* ptr;
ptr = fopen("Hello.txt", "r");
if (ptr == NULL)
{
printf("Error While opening file");
// if the pointer returns NULL
// program will exit
exit(1);
}
if(fgets(str, 80, ptr) != NULL)
{
puts(str);
}
fclose(ptr);
return 0;
}
Output:
2. Reading from a Binary File
fread() function also takes four arguments that are similar to fwrite() function in C Programming.
Syntax:
fwrite(const void *ptr,size_of_elements,number_of_elements, FILE *a_file);
Below is the C program to read from a binary file:
// C Program to Read from a
// binary file using fread()
#include <stdio.h>
#include <stdlib.h>
struct Num
{
int n1, n2;
};
// Driver code
int main()
{
int n;
struct Num obj;
FILE* fptr;
if ((fptr = fopen("temp.bin", "rb")) == NULL)
{
printf("Error! opening file");
// If file pointer will return NULL
// Program will exit.
exit(1);
}
// else it will return a pointer
// to the file.
for (n = 1; n < 10; ++n)
{
fread(&obj, sizeof(struct Num), 1, fptr);
printf("n1: %d\tn2: %d\n", obj.n1, obj.n2);
}
fclose(fptr);
return 0;
}
Output:
Explanation: In the above program, we have read the same file GFG.bin and are looping through records one by one. We read a single Num record of Num size from the file pointed by *fptr into the structure Num. We’ll get the same record that we inserted in the previous program.
C – File I/O
In this article, we will learn how to operate over files using a C program. A single C file can read, write, move, and create files in our computer easily using a few functions and elements included in the C File I/O system. We can easily manipulate data in a file regardless of whether the file is a text file or a binary file using functions like fopen(), fclose(), fprintf(), fscanf(), getc(), putc(), getw(), fseek(), etc.