C++ Read From File Into a String

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

  1. fgetc() This role is used to read a unmarried character from the file.
  2. fgets() This function is used to read strings from files.
  3. fscanf() This office 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 store the reference of the file in a FILE pointer.
  • Read contents of the file using whatever of these functions fgetc(), fgets(), fscanf(), or fread().
  • File close the file using the function fclose().

Let'southward brainstorm 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 character (ASCII value) read from the stream and advances the read position to the next character. This function returns a constant EOF (-1) 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 part by reading characters one past one.
  • Practice-While loop will be used which will read character until information technology reaches and of file.
  • When it reaches end it returns  EOF character (-i).

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

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

if (Nil == ptr) {

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

}

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

do {

ch = fgetc (ptr);

printf ( "%c" , ch);

} while (ch != EOF);

fclose (ptr);

render 0;

}

Input File:

GeeksforGeeks | A information science portal for geeks

Output:

output fgetc

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

Using feof():
feof() function takes file arrow as statement and returns true 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 cheque for end of file. since feof() returns true after it reaches the end.
  • Use logical Non operator(!) and so that when it reaches stop condition get 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 main()

{

FILE * ptr;

char ch;

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

if (Nix == ptr) {

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

}

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

while (! feof (ptr)) {

ch = fgetc (ptr);

printf ( "%c" , ch);

}

fclose (ptr);

return 0;

}

Input File:

GeeksforGeeks | A calculator science portal for geeks

Output:

output feof

fgets()

fgets() reads one string at a fourth dimension from the file. fgets() returns a cord if it is successfully read by function or returns NULL if tin can not read.

Syntax:

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

Here,
str: Information technology is cord in which fgets() store cord after reading it 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 i character at a time until we attain the end of the file.
  • When we reach the terminate of the file fgets() can't read and returns Nil and the program will terminate 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 ( "test.txt" , "a+" );

if (Nada == ptr) {

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

}

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

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

printf ( "%south" , str);

}

fclose (ptr);

return 0;

}

Input File:

GeeksforGeeks | A informatics 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 information in the buffer is printed on the console till the terminate of the file is reached.

C++

#include <stdio.h>

int principal()

{

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

if (ptr == Nada) {

printf ( "no such file." );

return 0;

}

char buf[100];

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

buf)

== 1)

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

render 0;

}

Output:

fread()

fread() makes it easier to read blocks of data from a file. For instance, 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 pointer to a block of memory with a minimum size of size*nmemb bytes.
size: This is the size in bytes of each chemical element to be 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.

Approach:

  • It first, reads the count number of objects, each i 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 re-create-able, so the behavior is undefined and if the value of size or count is equal to zero, and so this program will just render 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" , "w" );

if (of == Nil) {

fprintf (stderr,

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

leave (i);

}

struct Form inp1 = { "Algorithms" ,

"30OCT" };

struct Form inp2 = { "DataStructures" ,

"28SEPT" };

struct Course inp3 = { "Programming" ,

"1NOV" };

fwrite (&inp1, sizeof ( struct Class),

1, of);

fwrite (&inp2, sizeof ( struct Course),

1, of);

fwrite (&inp3, sizeof ( struct Course),

1, of);

if ( fwrite != 0)

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

else

printf ( "Mistake writing file !\north" );

fclose (of);

FILE * inf;

struct Course inp;

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

if (inf == NULL) {

fprintf (stderr,

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

exit (1);

}

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

1, inf))

printf ( "Course Proper name = %s Started = %southward\north" ,

inp.cname, inp.sdate);

fclose (inf);

}

Output:

output fread


rowallanwintakephe.blogspot.com

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

0 Response to "C++ Read From File Into a String"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel