How to Read Each Word From File in C
C programming language supports four pre-defined functions to read contents from a file, defined in stdio.h header file:
- fgetc() – This function is used to read a single graphic symbol from the file.
- fgets() – This function is used to read strings from files.
- fscanf() – This function is used to read the block of raw bytes from files. This is used to read binary files.
- fread() – This function is used to read formatted input from a file.
Steps To Read A File:
- Open a file using the part fopen() and shop the reference of the file in a FILE pointer.
- Read contents of the file using any of these functions fgetc(), fgets(), fscanf(), or fread().
- File close the file using the function fclose().
Allow's begin discussing each of these functions in detail.
fgetc()
fgetc() reads characters pointed by the part arrow at that time. On each successful read, it returns the character (ASCII value) read from the stream and advances the read position to the next character. This part returns a abiding EOF (-one) when at that place is no content to read or an unsuccessful read.
Syntax:
int fgetc(FILE *ptr);
Arroyo:
- This plan reads the whole content of the file, using this function by reading characters one past one.
- Practice-While loop will be used which will read graphic symbol until it reaches and of file.
- When it reaches stop it returns EOF grapheme (-i).
Using EOF:
Beneath is the C program to implement the in a higher place approach-
C
#include <stdio.h>
#include <stdlib.h>
#include <cord.h>
int master()
{
FILE * ptr;
char ch;
ptr = fopen ( "test.txt" , "r" );
if (Naught == ptr) {
printf ( "file can't be opened \n" );
}
printf ( "content of this file are \n" );
do {
ch = fgetc (ptr);
printf ( "%c" , ch);
} while (ch != EOF);
fclose (ptr);
return 0;
}
Input File:
GeeksforGeeks | A informatics portal for geeks
Output:
In the above code, the approach is to read i graphic symbol from the file and check if it is not EOF, if information technology is non then print it and if it is so terminate reading.
Using feof():
feof() function takes file pointer equally statement and returns true if pointer reaches the end of the file.
Syntax:
int feof(FILE *ptr);
Approach:
- In this approach, a grapheme is read using fgetc().
- Using feof() function cheque for terminate of file. since feof() returns truthful afterwards it reaches the end.
- Use logical NOT operator(!) and so that when it reaches finish status become fake and loop stop.
Below is the C program to implement the above approach:
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE * ptr;
char ch;
ptr = fopen ( "exam.txt" , "r" );
if (NULL == ptr) {
printf ( "file tin't be opened \due north" );
}
printf ( "content of this file are \n" );
while (! feof (ptr)) {
ch = fgetc (ptr);
printf ( "%c" , ch);
}
fclose (ptr);
return 0;
}
Input File:
GeeksforGeeks | A information science portal for geeks
Output:
fgets()
fgets() reads one string at a time from the file. fgets() returns a cord if it is successfully read by function or returns NULL if can not read.
Syntax:
char * fgets(char *str, int size, FILE * ptr);
Hither,
str: It is string in which fgets() shop string subsequently reading information technology from file.
size: It is maximum characters to read from stream.
ptr: It is file arrow.
Approach:
- In this approach, the contents of the file are read one grapheme at a time until we attain the terminate of the file.
- When we reach the end of the file fgets() can't read and returns Zero and the program will stop reading.
Beneath is the C program to implement the above approach:
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE * ptr;
char str[l];
ptr = fopen ( "test.txt" , "a+" );
if (Zip == ptr) {
printf ( "file can't exist opened \due north" );
}
printf ( "content of this file are \n" );
while ( fgets (str, 50, ptr) != Zero) {
printf ( "%s" , str);
}
fclose (ptr);
return 0;
}
Input File:
GeeksforGeeks | A reckoner scientific discipline portal for geeks
Output:
fscanf()
fscanf() reads formatted input from a stream.
Syntax:
int fscanf(FILE *ptr, const char *format, …)
Approach:
- fscanf reads formatted data from the files and stores it in variables.
- The information in the buffer is printed on the console till the end of the file is reached.
C++
#include <stdio.h>
int master()
{
FILE * ptr = fopen ( "abc.txt" , "r" );
if (ptr == NULL) {
printf ( "no such file." );
return 0;
}
char buf[100];
while ( fscanf (ptr, "%*s %*s %s " ,
buf)
== 1)
printf ( "%s\n" , buf);
return 0;
}
Output:
fread()
fread() makes it easier to read blocks of data from a file. For instance, in the example of reading a structure from the file, it becomes an easy job to read using fread.
Syntax:
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
ptr: This is the pointer to a block of memory with a minimum size of size*nmemb bytes.
size: This is the size in bytes of each element to be read.
nmemb: This is the number of elements, each one with a size of size bytes.
stream: This is the arrow to a FILE object that specifies an input stream.
Approach:
- It first, reads the count number of objects, each 1 with a size of size bytes from the given input stream.
- The full amount of bytes reads if successful is (size*count).
- Co-ordinate to the no. of characters read, the indicator file position is incremented.
- If the objects read are non trivially copy-able, then the behavior is undefined and if the value of size or count is equal to goose egg, then this program will but return 0.
C++
#include <stdio.h>
#include <stdlib.h>
#include <cord.h>
struct Grade {
char cname[thirty];
char sdate[30];
};
int main()
{
FILE * of;
of = fopen ( "examination.txt" , "w" );
if (of == Goose egg) {
fprintf (stderr,
"\nError to open the file\n" );
exit (1);
}
struct Course inp1 = { "Algorithms" ,
"30OCT" };
struct Course inp2 = { "DataStructures" ,
"28SEPT" };
struct Course inp3 = { "Programming" ,
"1NOV" };
fwrite (&inp1, sizeof ( struct Form),
1, of);
fwrite (&inp2, sizeof ( struct Class),
1, of);
fwrite (&inp3, sizeof ( struct Course),
1, of);
if ( fwrite != 0)
printf ( "Contents to file written successfully !\north" );
else
printf ( "Error writing file !\n" );
fclose (of);
FILE * inf;
struct Form inp;
inf = fopen ( "examination.txt" , "r" );
if (inf == NULL) {
fprintf (stderr,
"\nError to open the file\n" );
go out (ane);
}
while ( fread (&inp, sizeof ( struct Course),
1, inf))
printf ( "Course Proper name = %s Started = %s\due north" ,
inp.cname, inp.sdate);
fclose (inf);
}
Output:
Source: https://www.geeksforgeeks.org/c-program-to-read-contents-of-whole-file/
إرسال تعليق for "How to Read Each Word From File in C"