How to Read in a File Until Empty C++

C programming language supports four pre-defined functions to read contents from a file, defined in stdio.h header file:

  1. fgetc() This part is used to read a single character from the file.
  2. fgets() This function is used to read strings from files.
  3. fscanf() This function is used to read the block of raw bytes from files. This is used to read binary files.
  4. fread() This office is used to read formatted input from a file.

Steps To Read A File:

  • Open up a file using the function fopen() and shop the reference of the file in a FILE arrow.
  • Read contents of the file using any of these functions fgetc(), fgets(), fscanf(), or fread().
  • File close the file using the role fclose().

Permit's begin discussing each of these functions in detail.

fgetc()

fgetc() reads characters pointed past the office 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 constant EOF (-i) when there is no content to read or an unsuccessful read.

Syntax:

int fgetc(FILE *ptr);

Approach:

  • This program reads the whole content of the file, using this function by reading characters one past one.
  • Exercise-While loop will be used which volition read character until it reaches and of file.
  • When it reaches cease it returns  EOF grapheme (-ane).

Using EOF:
Below is the C program to implement the above approach-

C

#include <stdio.h>

#include <stdlib.h>

#include <cord.h>

int principal()

{

FILE * ptr;

char ch;

ptr = fopen ( "exam.txt" , "r" );

if (Zippo == ptr) {

printf ( "file can't be opened \due north" );

}

printf ( "content of this file are \due north" );

do {

ch = fgetc (ptr);

printf ( "%c" , ch);

} while (ch != EOF);

fclose (ptr);

return 0;

}

Input File:

GeeksforGeeks | A figurer science portal for geeks

Output:

output fgetc

In the above lawmaking, the approach is to read one graphic symbol from the file and check if it is not EOF, if it is not so print it and if information technology is and so terminate reading.

Using feof():
feof() role takes file pointer every bit argument and returns truthful if pointer reaches the end of the file.

Syntax:

int feof(FILE *ptr);

Arroyo:

  • In this approach, a graphic symbol is read using fgetc().
  • Using feof() part check for cease of file. since feof() returns true subsequently it reaches the stop.
  • Use logical Non operator(!) then that when information technology reaches finish condition become fake and loop terminate.

Below is the C program to implement the higher up approach:

C

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

int principal()

{

FILE * ptr;

char ch;

ptr = fopen ( "examination.txt" , "r" );

if (NULL == ptr) {

printf ( "file tin't be opened \n" );

}

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:

output feof

fgets()

fgets() reads i string at a time from the file. fgets() returns a string if it is successfully read by part or returns Zilch if tin not read.

Syntax:

char * fgets(char *str, int size, FILE * ptr);

Here,
str: Information technology is string in which fgets() store string after reading information technology from file.
size: It is maximum characters to read from stream.
ptr: Information technology is file pointer.

Arroyo:

  • In this approach, the contents of the file are read one character at a fourth dimension until we reach the end of the file.
  • When we attain the end of the file fgets() can't read and returns NULL and the program will cease reading.

Beneath is the C programme to implement the higher up arroyo:

C

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

int main()

{

FILE * ptr;

char str[50];

ptr = fopen ( "test.txt" , "a+" );

if (Zip == ptr) {

printf ( "file tin't be opened \due north" );

}

printf ( "content of this file are \due north" );

while ( fgets (str, l, ptr) != NULL) {

printf ( "%southward" , str);

}

fclose (ptr);

return 0;

}

Input File:

GeeksforGeeks | A computer science portal for geeks

Output:

Output fgets

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 data in the buffer is printed on the console till the end of the file is reached.

C++

#include <stdio.h>

int principal()

{

FILE * ptr = fopen ( "abc.txt" , "r" );

if (ptr == Cypher) {

printf ( "no such file." );

return 0;

}

char buf[100];

while ( fscanf (ptr, "%*s %*south %s " ,

buf)

== 1)

printf ( "%s\due north" , buf);

return 0;

}

Output:

fread()

fread() makes it easier to read blocks of data from a file. For instance, in the case of reading a structure from the file, it becomes an easy task 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 1 with a size of size bytes.
stream: This is the pointer to a FILE object that specifies an input stream.

Arroyo:

  • It start, 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).
  • 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 zippo, then this program will simply return 0.

C++

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

struct Form {

char cname[30];

char sdate[30];

};

int chief()

{

FILE * of;

of = fopen ( "examination.txt" , "due west" );

if (of == Nix) {

fprintf (stderr,

"\nError to open the file\north" );

go out (1);

}

struct Class inp1 = { "Algorithms" ,

"30OCT" };

struct Course inp2 = { "DataStructures" ,

"28SEPT" };

struct Course inp3 = { "Programming" ,

"1NOV" };

fwrite (&inp1, sizeof ( struct Grade),

1, of);

fwrite (&inp2, sizeof ( struct Grade),

1, of);

fwrite (&inp3, sizeof ( struct Grade),

one, of);

if ( fwrite != 0)

printf ( "Contents to file written successfully !\north" );

else

printf ( "Error writing file !\n" );

fclose (of);

FILE * inf;

struct Course inp;

inf = fopen ( "test.txt" , "r" );

if (inf == NULL) {

fprintf (stderr,

"\nError to open up the file\northward" );

exit (1);

}

while ( fread (&inp, sizeof ( struct Course),

1, inf))

printf ( "Course Name = %s Started = %s\n" ,

inp.cname, inp.sdate);

fclose (inf);

}

Output:

output fread


petersonswassed.blogspot.com

Source: https://www.geeksforgeeks.org/c-program-to-read-contents-of-whole-file/

0 Response to "How to Read in a File Until Empty C++"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel