Read a File Line by Line C++
C programming linguistic communication supports four pre-divers functions to read contents from a file, defined in stdio.h header file:
- fgetc() – This function is used to read a unmarried grapheme from the file.
- fgets() – This function is used to read strings from files.
- fscanf() – This part 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 office 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 shut the file using the function fclose().
Let's begin discussing each of these functions in detail.
fgetc()
fgetc() reads characters pointed by the function pointer at that time. On each successful read, it returns the grapheme (ASCII value) read from the stream and advances the read position to the next character. This function returns a abiding 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 1 by i.
- Practice-While loop will be used which will read grapheme until it reaches and of file.
- When it reaches terminate it returns EOF graphic symbol (-1).
Using EOF:
Below is the C plan to implement the in a higher place approach-
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE * ptr;
char ch;
ptr = fopen ( "test.txt" , "r" );
if (NULL == ptr) {
printf ( "file can't be opened \n" );
}
printf ( "content of this file are \due north" );
practise {
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 cheque if it is non EOF, if it is non then impress it and if information technology is then stop reading.
Using feof():
feof() part takes file pointer equally statement and returns true if arrow reaches the end of the file.
Syntax:
int feof(FILE *ptr);
Approach:
- In this approach, a character is read using fgetc().
- Using feof() part cheque for end of file. since feof() returns true after information technology reaches the stop.
- Use logical NOT operator(!) and so that when it reaches end condition go false and loop finish.
Beneath is the C program to implement the in a higher place approach:
C
#include <stdio.h>
#include <stdlib.h>
#include <cord.h>
int main()
{
FILE * ptr;
char ch;
ptr = fopen ( "test.txt" , "r" );
if (NULL == ptr) {
printf ( "file can't be opened \n" );
}
printf ( "content of this file are \n" );
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 one cord at a time from the file. fgets() returns a string if it is successfully read past function or returns NULL if can non read.
Syntax:
char * fgets(char *str, int size, FILE * ptr);
Here,
str: Information technology is string in which fgets() store string after reading it from file.
size: It is maximum characters to read from stream.
ptr: It is file pointer.
Approach:
- In this arroyo, the contents of the file are read one character at a time until we reach the end of the file.
- When we accomplish the cease of the file fgets() can't read and returns Nil and the program volition stop reading.
Beneath is the C program to implement the above arroyo:
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE * ptr;
char str[fifty];
ptr = fopen ( "exam.txt" , "a+" );
if (NULL == ptr) {
printf ( "file can't be opened \n" );
}
printf ( "content of this file are \due north" );
while ( fgets (str, 50, ptr) != NULL) {
printf ( "%s" , str);
}
fclose (ptr);
return 0;
}
Input File:
GeeksforGeeks | A information science portal for geeks
Output:
fscanf()
fscanf() reads formatted input from a stream.
Syntax:
int fscanf(FILE *ptr, const char *format, …)
Arroyo:
- fscanf reads formatted data from the files and stores it in variables.
- The data in the buffer is printed on the console till the end of the file is reached.
C++
#include <stdio.h>
int main()
{
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)
== one)
printf ( "%south\north" , buf);
return 0;
}
Output:
fread()
fread() makes it easier to read blocks of information from a file. For example, in the case 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 be read.
nmemb: This is the number of elements, each ane with a size of size bytes.
stream: This is the pointer to a FILE object that specifies an input stream.
Approach:
- It offset, reads the count number of objects, each one with a size of size bytes from the given input stream.
- The total corporeality of bytes reads if successful is (size*count).
- According to the no. of characters read, the indicator file position is incremented.
- If the objects read are not trivially copy-able, and then the behavior is undefined and if the value of size or count is equal to zip, then this plan will but return 0.
C++
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Course {
char cname[30];
char sdate[30];
};
int main()
{
FILE * of;
of = fopen ( "test.txt" , "westward" );
if (of == Goose egg) {
fprintf (stderr,
"\nError to open the file\n" );
leave (one);
}
struct Course inp1 = { "Algorithms" ,
"30OCT" };
struct Grade inp2 = { "DataStructures" ,
"28SEPT" };
struct Form inp3 = { "Programming" ,
"1NOV" };
fwrite (&inp1, sizeof ( struct Form),
1, of);
fwrite (&inp2, sizeof ( struct Course),
one, of);
fwrite (&inp3, sizeof ( struct Class),
i, of);
if ( fwrite != 0)
printf ( "Contents to file written successfully !\due north" );
else
printf ( "Fault writing file !\n" );
fclose (of);
FILE * inf;
struct Course inp;
inf = fopen ( "test.txt" , "r" );
if (inf == NULL) {
fprintf (stderr,
"\nError to open the file\n" );
exit (one);
}
while ( fread (&inp, sizeof ( struct Course),
1, inf))
printf ( "Grade Proper noun = %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 a File Line by Line C++"
Post a Comment