Read File Into a String in C

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

  1. fgetc() This office is used to read a single character from the file.
  2. fgets() This office 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 part 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().

Let'south begin discussing each of these functions in item.

fgetc()

fgetc() reads characters pointed by the role pointer at that time. On each successful read, information technology returns the character (ASCII value) read from the stream and advances the read position to the adjacent character. This office returns a abiding EOF (-1) 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 function by reading characters one by i.
  • Practise-While loop will exist used which volition read graphic symbol until information technology reaches and of file.
  • When it reaches cease it returns  EOF graphic symbol (-one).

Using EOF:
Below is the C program 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 (Naught == ptr) {

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

}

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

do {

ch = fgetc (ptr);

printf ( "%c" , ch);

} while (ch != EOF);

fclose (ptr);

return 0;

}

Input File:

GeeksforGeeks | A computer science portal for geeks

Output:

output fgetc

In the higher up lawmaking, the approach is to read ane grapheme from the file and check if it is not EOF, if it is not and then impress information technology and if it is then finish reading.

Using feof():
feof() function takes file arrow equally argument and returns truthful if pointer reaches the terminate of the file.

Syntax:

int feof(FILE *ptr);

Arroyo:

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

Below is the C program to implement the above arroyo:

C

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

int primary()

{

FILE * ptr;

char ch;

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

if (Nil == ptr) {

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

}

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 cord at a time from the file. fgets() returns a string if it is successfully read by office or returns Goose egg if can not read.

Syntax:

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

Hither,
str: It 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 arrow.

Approach:

  • In this arroyo, the contents of the file are read ane character at a time until nosotros reach the terminate of the file.
  • When we reach the stop of the file fgets() tin't read and returns NULL and the program will stop reading.

Below is the C program to implement the above arroyo:

C

#include <stdio.h>

#include <stdlib.h>

#include <cord.h>

int main()

{

FILE * ptr;

char str[50];

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

if (Nada == ptr) {

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

}

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

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

printf ( "%s" , 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 information in the buffer is printed on the panel till the end of the file is reached.

C++

#include <stdio.h>

int main()

{

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

if (ptr == Zero) {

printf ( "no such file." );

return 0;

}

char buf[100];

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

buf)

== one)

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

render 0;

}

Output:

fread()

fread() makes it easier to read blocks of data from a file. For example, in the case of reading a structure from the file, it becomes an like shooting fish in a barrel 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 retention 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 first, reads the count number of objects, each one with a size of size bytes from the given input stream.
  • The full 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 non 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 just return 0.

C++

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

struct Course {

char cname[30];

char sdate[thirty];

};

int main()

{

FILE * of;

of = fopen ( "test.txt" , "west" );

if (of == NULL) {

fprintf (stderr,

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

get out (1);

}

struct Form inp1 = { "Algorithms" ,

"30OCT" };

struct Grade inp2 = { "DataStructures" ,

"28SEPT" };

struct Course inp3 = { "Programming" ,

"1NOV" };

fwrite (&inp1, sizeof ( struct Course),

one, of);

fwrite (&inp2, sizeof ( struct Form),

1, of);

fwrite (&inp3, sizeof ( struct Class),

one, of);

if ( fwrite != 0)

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

else

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

fclose (of);

FILE * inf;

struct Course inp;

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

if (inf == NULL) {

fprintf (stderr,

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

go out (1);

}

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

1, inf))

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

inp.cname, inp.sdate);

fclose (inf);

}

Output:

output fread


mcintyrehinge1963.blogspot.com

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

0 Response to "Read File Into a String in C"

Publicar un comentario

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel