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