Ask Sawal

Discussion Forum
Notification Icon1
Write Answer Icon
Add Question Icon

How to read in a file c++?

2 Answer(s) Available
Answer # 1 #
  • Create a stream object.
  • Connect it to a file on disk.
  • Read the file's contents into our stream object.
  • Close the file.
[4]
Edit
Query
Report
Kashif dmibpjnh Jannik
PATCH WASHER
Answer # 2 #

Steps To Read A File:

Let’s begin 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:

Approach:

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

Input File:

Output:

In the above code, the approach is to read one character from the file and check if it is not EOF, if it is not then print it and if it is then stop reading.

Using feof():feof() function takes file pointer as argument and returns true if pointer reaches the end of the file.

Syntax:

Approach:

Below is the C program to implement the above approach:

Input File:

Output:

fgets()

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

Syntax:

Approach:

Below is the C program to implement the above approach:

Input File:

Output:

fscanf()

fscanf() reads formatted input from a stream.

Syntax:

Approach:

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 job to read using fread.

Syntax:

Approach:

Output:

[2]
Edit
Query
Report
Mukul Bardhan
PRINTED CIRCUIT DESIGNER