C Programming How to Read Strings From a File Into Array

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

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

Steps To Read A File:

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

Let's brainstorm discussing each of these functions in item.

fgetc()

fgetc() reads characters pointed by the role pointer at that fourth dimension. On each successful read, it returns the character (ASCII value) read from the stream and advances the read position to the side by side 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 office by reading characters ane past one.
  • Do-While loop will be used which volition read graphic symbol until it reaches and of file.
  • When it reaches end it returns  EOF character (-1).

Using EOF:
Below is the C plan 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 can't be opened \n" );

}

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

do {

ch = fgetc (ptr);

printf ( "%c" , ch);

} while (ch != EOF);

fclose (ptr);

return 0;

}

Input File:

GeeksforGeeks | A information science portal for geeks

Output:

output fgetc

In the above lawmaking, the approach is to read i character from the file and cheque if information technology is not EOF, if it is not then print it and if it is so finish reading.

Using feof():
feof() function takes file pointer as statement and returns truthful 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 check for end of file. since feof() returns true after information technology reaches the cease.
  • Use logical Non operator(!) so that when it reaches end condition get faux 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 ( "exam.txt" , "r" );

if (NULL == ptr) {

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

}

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

while (! feof (ptr)) {

ch = fgetc (ptr);

printf ( "%c" , ch);

}

fclose (ptr);

render 0;

}

Input File:

GeeksforGeeks | A computer scientific discipline portal for geeks

Output:

output feof

fgets()

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

Syntax:

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

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

Approach:

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

Below is the C program to implement the in a higher place approach:

C

#include <stdio.h>

#include <stdlib.h>

#include <cord.h>

int chief()

{

FILE * ptr;

char str[50];

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

if (NULL == ptr) {

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

}

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

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

printf ( "%s" , str);

}

fclose (ptr);

render 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 information from the files and stores it in variables.
  • The data in the buffer is printed on the console till the terminate of the file is reached.

C++

#include <stdio.h>

int master()

{

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

if (ptr == NULL) {

printf ( "no such file." );

return 0;

}

char buf[100];

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

buf)

== i)

printf ( "%s\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 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 one with a size of size bytes.
stream: This is the pointer to a FILE object that specifies an input stream.

Arroyo:

  • 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).
  • 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 nil, then this plan will only return 0.

C++

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

struct Form {

char cname[xxx];

char sdate[30];

};

int main()

{

FILE * of;

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

if (of == Nada) {

fprintf (stderr,

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

exit (1);

}

struct Class inp1 = { "Algorithms" ,

"30OCT" };

struct Course inp2 = { "DataStructures" ,

"28SEPT" };

struct Course inp3 = { "Programming" ,

"1NOV" };

fwrite (&inp1, sizeof ( struct Class),

i, of);

fwrite (&inp2, sizeof ( struct Grade),

1, of);

fwrite (&inp3, sizeof ( struct Grade),

1, of);

if ( fwrite != 0)

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

else

printf ( "Fault writing file !\due north" );

fclose (of);

FILE * inf;

struct Class inp;

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

if (inf == NULL) {

fprintf (stderr,

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

exit (1);

}

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

1, inf))

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

inp.cname, inp.sdate);

fclose (inf);

}

Output:

output fread


crossonotigh1954.blogspot.com

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

0 Response to "C Programming How to Read Strings From a File Into Array"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel