Read File String and Integers C Programming
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 character from the file.
- fgets() – This part is used to read strings from files.
- fscanf() – This role 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 function fopen() and store 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 part fclose().
Permit'southward begin discussing each of these functions in detail.
fgetc()
fgetc() reads characters pointed by the function arrow at that fourth dimension. On each successful read, it returns the character (ASCII value) read from the stream and advances the read position to the next character. This role returns a constant EOF (-1) when there is no content to read or an unsuccessful read.
Syntax:
int fgetc(FILE *ptr);
Arroyo:
- This program reads the whole content of the file, using this function by reading characters one past 1.
- Practice-While loop will be used which volition read character until it reaches and of file.
- When information technology reaches cease information technology returns EOF character (-1).
Using EOF:
Below is the C program to implement the above approach-
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int chief()
{
FILE * ptr;
char ch;
ptr = fopen ( "test.txt" , "r" );
if (Goose egg == ptr) {
printf ( "file tin'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 computer scientific discipline portal for geeks
Output:
In the above lawmaking, the arroyo is to read one graphic symbol from the file and check if it is not EOF, if information technology is not then impress information technology and if it is then stop reading.
Using feof():
feof() part takes file arrow as argument and returns truthful if pointer reaches the end of the file.
Syntax:
int feof(FILE *ptr);
Approach:
- In this approach, a character is read using fgetc().
- Using feof() function check for end of file. since feof() returns true after it reaches the end.
- Use logical NOT operator(!) so that when information technology reaches end condition become imitation and loop end.
Below is the C plan to implement the higher up approach:
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int master()
{
FILE * ptr;
char ch;
ptr = fopen ( "test.txt" , "r" );
if (Zippo == ptr) {
printf ( "file can't be opened \due north" );
}
printf ( "content of this file are \north" );
while (! feof (ptr)) {
ch = fgetc (ptr);
printf ( "%c" , ch);
}
fclose (ptr);
render 0;
}
Input File:
GeeksforGeeks | A information science portal for geeks
Output:
fgets()
fgets() reads ane string at a fourth dimension from the file. fgets() returns a cord if it is successfully read by role or returns Null if can not read.
Syntax:
char * fgets(char *str, int size, FILE * ptr);
Here,
str: It is string in which fgets() store string after reading it from file.
size: Information technology is maximum characters to read from stream.
ptr: It is file pointer.
Arroyo:
- In this approach, the contents of the file are read one grapheme at a time until we reach the end of the file.
- When nosotros reach the stop of the file fgets() can't read and returns NULL and the program volition cease reading.
Below is the C plan to implement the higher up approach:
C
#include <stdio.h>
#include <stdlib.h>
#include <cord.h>
int main()
{
FILE * ptr;
char str[50];
ptr = fopen ( "test.txt" , "a+" );
if (Zilch == ptr) {
printf ( "file can't exist opened \n" );
}
printf ( "content of this file are \n" );
while ( fgets (str, 50, ptr) != NULL) {
printf ( "%southward" , str);
}
fclose (ptr);
return 0;
}
Input File:
GeeksforGeeks | A computer 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 information from the files and stores it in variables.
- The information in the buffer is printed on the console till the finish of the file is reached.
C++
#include <stdio.h>
int chief()
{
FILE * ptr = fopen ( "abc.txt" , "r" );
if (ptr == Zilch) {
printf ( "no such file." );
return 0;
}
char buf[100];
while ( fscanf (ptr, "%*s %*south %s " ,
buf)
== 1)
printf ( "%s\n" , buf);
return 0;
}
Output:
fread()
fread() makes information technology easier to read blocks of data from a file. For example, in the instance 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 arrow to a block of memory with a minimum size of size*nmemb bytes.
size: This is the size in bytes of each element to exist read.
nmemb: This is the number of elements, each one with a size of size bytes.
stream: This is the pointer to a FILE object that specifies an input stream.
Arroyo:
- It offset, reads the count number of objects, each one with a size of size bytes from the given input stream.
- The total 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 not trivially copy-able, and so the behavior is undefined and if the value of size or count is equal to zero, then this program will merely return 0.
C++
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Course {
char cname[thirty];
char sdate[30];
};
int principal()
{
FILE * of;
of = fopen ( "exam.txt" , "w" );
if (of == NULL) {
fprintf (stderr,
"\nError to open the file\north" );
get out (one);
}
struct Course inp1 = { "Algorithms" ,
"30OCT" };
struct Class inp2 = { "DataStructures" ,
"28SEPT" };
struct Course inp3 = { "Programming" ,
"1NOV" };
fwrite (&inp1, sizeof ( struct Course),
ane, of);
fwrite (&inp2, sizeof ( struct Grade),
1, of);
fwrite (&inp3, sizeof ( struct Class),
one, of);
if ( fwrite != 0)
printf ( "Contents to file written successfully !\north" );
else
printf ( "Error writing file !\north" );
fclose (of);
FILE * inf;
struct Form inp;
inf = fopen ( "test.txt" , "r" );
if (inf == NULL) {
fprintf (stderr,
"\nError to open up the file\northward" );
exit (one);
}
while ( fread (&inp, sizeof ( struct Course),
1, inf))
printf ( "Course Name = %s Started = %s\n" ,
inp.cname, inp.sdate);
fclose (inf);
}
Output:
Source: https://www.geeksforgeeks.org/c-program-to-read-contents-of-whole-file/
0 Response to "Read File String and Integers C Programming"
Post a Comment