The ones who are crazy enough to think they can change the world are the ones who do.- Steve Jobs
The following functions are used to read data from the files.
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.
Lets try to code using fscanf() and have some fun.
#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; }
The rewind function resets the pointer to the starting point of a file.
The fgetc() function used to read a single character from a file. It can read only one character at a time.
Lets try to code using fgetc() and have some fun.
#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; }
The program illustrates that the fgetc function reads the character one by one and print the character one by one using putchar function.
The fgets() function used to read a string from a file.
Lets try to code using fgets() and have some fun.
#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; }
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.
We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.
© Copyright 2019