Reading Data From a File in C Programing

As we have seen in the earlier articles, to create a file and write information to a file, we can also read the stored data from a file. There are three different steps to read data from a file, they are:

fgetc(file_pointer): 

It returns the next character from the file pointed to by the file pointer. When the pointer reaches the end of the file the operation terminates.

fgets(buffer, n, file_pointer): 

It reads n-1 characters from the file and stores the string in a buffer in which a NULL character ‘\0’ is appended as the last character.

fscanf(file_pointer, conversion_specifiers, variable_adresses):

It is used to parse and analyze data. It reads characters from the file and assigns the input to a list of variable pointers variable addresses using conversion specifiers.

Let us see an example to get things cleared.

#include <stdio.h>
int main() {
        FILE *ptr;
        char str[30], c;
		//Using fgets()
        ptr = fopen("test.txt", "r");
        printf("Reading data using fgets()\n");
        fgets(str, 50, ptr);
        printf("%s\n", str);
		//Using fscanf()
        printf("Reading data using fscanf()\n");
        ptr = fopen("test.txt", "r");
        char str1[10], str2[20], str3[30], str4[40];
        fscanf(ptr, "%s %s %s %s", str1, str2, str3, str4);
        printf("%s\n", str1);
        printf("%s\n", str2);
        printf("%s\n", str3);
        printf("%s\n", str4);
		//Using getc()
        printf("\nReading the file using getc()\n");
        ptr = fopen("test.txt", "r");
        while ((c = getc(ptr)) != EOF) 
		printf("%c", c);
 
        fclose(ptr);
        return 0;
    }

Join Our Community

Join our WhatsApp Group To know more About Programming Language tips, tricks and knowledge about programming and how to start learning any programming language.

Output:

Reading data using fgets()
Hi, Welcome To LingarajTechhub
Reading data using fscanf()
Hi,
Welcome
To
LingarajTechhub

C7UbXT5qOekcDF43eSelcDDNw2SzYWxg0f gKZ wiBeEVtXZcMCENxVdjdlrmPXdE84aRcgVWghjWYOC Qb nmLPWPHFYmiIpTl7ankNiI0yVvWpS5DS7nm 62tIFach1p3Gkw

Default image
Soham Malakar
Hello my name is Soham Malakar am currently pursuing BCA Coding is one of my favorite hobbies. I love to code and an enthusiast to learn different types of programming languages. I love to get intoxicated in the world of technology and video games. A quick learner possessing better results.
Articles: 40

Newsletter Updates

Enter your email address below to subscribe to our newsletter

Leave a Reply