C++ Program to Read a File Character by Character

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

  1. fgetc() This function is used to read a single graphic symbol 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 function is used to read formatted input from a file.

Steps To Read A File:

  • Open a file using the function 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 shut the file using the function fclose().

Allow's begin discussing each of these functions in item.

fgetc()

fgetc() reads characters pointed by the office pointer at that time. On each successful read, it returns the graphic symbol (ASCII value) read from the stream and advances the read position to the next graphic symbol. This office returns a constant EOF (-one) when in that location 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 office by reading characters one by one.
  • Do-While loop will be used which will read character until it reaches and of file.
  • When it reaches end it returns  EOF character (-i).

Using EOF:
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 ch;

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

if (NULL == ptr) {

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

}

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

do {

ch = fgetc (ptr);

printf ( "%c" , ch);

} while (ch != EOF);

fclose (ptr);

render 0;

}

Input File:

GeeksforGeeks | A computer scientific discipline portal for geeks

Output:

output fgetc

In the to a higher place code, the approach is to read ane character from the file and check if it is not EOF, if information technology is not then print it and if it is then finish reading.

Using feof():
feof() office takes file pointer as argument and returns true if arrow reaches the stop of the file.

Syntax:

int feof(FILE *ptr);

Approach:

  • In this approach, a character is read using fgetc().
  • Using feof() function check for cease of file. since feof() returns true after it reaches the end.
  • Utilise logical Not operator(!) so that when it reaches end condition become false and loop stop.

Below is the C program to implement the above approach:

C

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

int master()

{

FILE * ptr;

char ch;

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

if (NULL == ptr) {

printf ( "file tin can't exist 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 reckoner science portal for geeks

Output:

output feof

fgets()

fgets() reads one string at a time from the file. fgets() returns a cord if it is successfully read past role or returns Goose egg if can not read.

Syntax:

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

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

Approach:

  • 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 reach the end of the file fgets() can't read and returns NULL and the plan will finish 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[50];

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

if (Nada == ptr) {

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

}

printf ( "content of this file are \n" );

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

printf ( "%south" , 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, …)

Arroyo:

  • fscanf reads formatted data from the files and stores it in variables.
  • The data in the buffer is printed on the panel till the end of the file is reached.

C++

#include <stdio.h>

int primary()

{

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

if (ptr == Naught) {

printf ( "no such file." );

render 0;

}

char buf[100];

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

buf)

== one)

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

render 0;

}

Output:

fread()

fread() makes information technology easier to read blocks of data from a file. For case, 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 i 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 ane 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, then the beliefs is undefined and if the value of size or count is equal to zero, and so 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 main()

{

FILE * of;

of = fopen ( "exam.txt" , "w" );

if (of == NULL) {

fprintf (stderr,

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

exit (one);

}

struct Grade inp1 = { "Algorithms" ,

"30OCT" };

struct Form inp2 = { "DataStructures" ,

"28SEPT" };

struct Grade inp3 = { "Programming" ,

"1NOV" };

fwrite (&inp1, sizeof ( struct Class),

1, of);

fwrite (&inp2, sizeof ( struct Grade),

1, of);

fwrite (&inp3, sizeof ( struct Form),

ane, of);

if ( fwrite != 0)

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

else

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

fclose (of);

FILE * inf;

struct Course inp;

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

if (inf == Naught) {

fprintf (stderr,

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

exit (1);

}

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

1, inf))

printf ( "Class Name = %s Started = %southward\n" ,

inp.cname, inp.sdate);

fclose (inf);

}

Output:

output fread


mitchellspeausell.blogspot.com

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

0 Response to "C++ Program to Read a File Character by Character"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel