C Programming • Pointers & File handling
C Programming / Reading from files

Reading from files

Notes 5 Pointers & File handling

Reading from a file means retrieving data that has already been stored in a file. In C, a file is first opened in an appropriate mode and then functions such as fgetc(), fgets() or fscanf() can be used to read its contents.

Notes

Reading from a file means retrieving data that has already been stored in a file. In C, a file is first opened in an appropriate mode and then functions such as fgetc(), fgets() or fscanf() can be used to read its contents.

💡 Example
FILE *fp; fp = fopen("student.txt", "r");

The file student.txt is opened in read mode so that its existing contents can be read.

Reading Using a File Pointer

After a file is opened successfully, the program works with the file through its file pointer. The pointer keeps track of the current position from which the next data will be read.

💡 Example
FILE *fp; fp = fopen("data.txt", "r");

After opening the file, fp is used for subsequent reading operations.

fgetc() Function

The fgetc() function reads one character from the current position of an opened file. After reading the character, the file position moves forward to the next character.

💡 Example
int ch; ch = fgetc(fp);

One character is read from the file referred to by fp.

Reading Character by Character

A file can be read character by character by repeatedly calling fgetc(). The reading continues until the end of the file is reached.

💡 Example
while ((ch = fgetc(fp)) != EOF) { printf("%c", ch); }

Each character is read and displayed until fgetc() indicates that the end of the file has been reached.

EOF — End of File

EOF is used to indicate that the end of the file has been reached during a reading operation. When fgetc() reaches the end of the file, it returns EOF, allowing the loop to stop.

💡 Example
while ((ch = fgetc(fp)) != EOF) { printf("%c", ch); }

The loop continues while the returned character is not EOF.

Why Use int for fgetc() Result?

The value returned by fgetc() is commonly stored in an int variable because the function must be able to represent every possible character value as well as the special EOF value.

💡 Example
int ch; ch = fgetc(fp);

The int variable can hold both an input character value and EOF.

fgets() Function

The fgets() function is used to read a string or line of text from a file. Unlike fgetc(), which reads one character at a time, fgets() can read multiple characters into a character array.

💡 Example
char line[100]; fgets(line, sizeof(line), fp);

A line of text is read from the file into the character array line.

fscanf() Function

The fscanf() function is used to read formatted data from a file. It works similarly to scanf(), but the input is taken from a file through the file pointer.

💡 Example
fscanf(fp, "%s %d", name, &age);

Formatted values are read from the file represented by fp.

Checking Whether the File Opened Successfully

Before reading a file, the program should verify that fopen() returned a valid file pointer. If the file cannot be opened, the function returns NULL.

⚠️ Example
fp = fopen("student.txt", "r"); if (fp == NULL) { printf("Cannot open file "); return 1; }

This prevents the program from attempting to read from an invalid file pointer.

Closing the File

After all reading operations are finished, the file should be closed using fclose(). Closing the file releases the resources associated with the opened file.

💡 Example
fclose(fp);

Basic Reading Flow

Declare FILE pointer ↓ Open file using "r" ↓ Check for NULL ↓ Read file contents ↓ Check EOF when required ↓ Close file

Practical Example

Problem Statement

Write a C program to open an existing text file and display its contents character by character.

Learning Outcomes

  • Open a text file in read mode.
  • Read characters using fgetc().
  • Use EOF to detect the end of the file.
  • Close the file after reading.

Hint

Open student.txt using "r" mode, use fgetc() inside a loop, and continue until EOF is returned.

Theory

The fgetc() function reads one character at a time from the current file position. Every successful read advances the position to the next character. When the end of the file is reached, fgetc() returns EOF.

File Content

Welcome to BCA Study Portal. C Programming is easy with practice.

Program

#include <stdio.h> int main() { FILE *fp; int ch; // open the file in read mode fp = fopen("student.txt", "r"); // check whether the file was opened successfully if (fp == NULL) { printf("Cannot open file "); return 1; } printf("File Contents: "); // read and display the file character by character while ((ch = fgetc(fp)) != EOF) { printf("%c", ch); } // close the file after reading fclose(fp); return 0; }

Expected Output

File Contents:

Welcome to BCA Study Portal.

C Programming is easy with practice.

Note

In this program, fp refers to the opened file and fgetc() reads one character at a time. The loop ends when EOF is returned.

Practical Example — Reading a Record

When a file contains structured records, formatted reading can be performed using fscanf(). This allows values such as names, ages, and marks to be read according to a specified format.

💡 Example
fscanf(fp, "%s %d %f", name, &age, &marks);

The statement reads a string, an integer and a floating-point value from the file.

Sample File

Rahul 20 78.5 Priya 21 86.0 Aman 20 81.5

Program

#include <stdio.h> int main() { FILE *fp; char name[30]; int age; float marks; // open the record file for reading fp = fopen("students.txt", "r"); // check whether the file was opened successfully if (fp == NULL) { printf("Cannot open file "); return 1; } printf("Student Records: "); // read records until the end of the file while (fscanf(fp, "%29s %d %f", name, &age, &marks) == 3) { printf("Name = %s, Age = %d, Marks = %.1f ", name, age, marks); } fclose(fp); return 0; }

Expected Output

Student Records:

Name = Rahul, Age = 20, Marks = 78.5

Name = Priya, Age = 21, Marks = 86.0

Name = Aman, Age = 20, Marks = 81.5

Note

fscanf() is useful when the file contains data in a known format. The program checks whether all three expected values were successfully read before processing the record.

Reading Functions at a Glance

Function Main Use
fgetc() Reads one character from a file.
fgets() Reads a line or string from a file.
fscanf() Reads formatted data from a file.
feof() Tests whether the end-of-file indicator is set.

Important Difference: fgetc() and fgets()

📌 Remember

fgetc() → reads one character at a time.

fgets() → reads a string or line into a character array.

Common Mistakes

⚠️ Mistake 1

Trying to read from a file without checking whether fopen() returned NULL.

⚠️ Mistake 2

Using a character variable for the result of fgetc() can make it impossible to distinguish every valid character value from EOF. Use an int variable when checking for EOF.

⚠️ Mistake 3

Forgetting to close the file after completing the reading operation.

Quick Revision

Concept Remember
Read Mode "r"
File Pointer FILE *fp
Single Character fgetc(fp)
String / Line fgets()
Formatted Data fscanf()
End of File EOF
Close File fclose(fp)

Important Exam Questions

Short Answer Questions

  1. What is meant by reading from a file?
  2. What is the use of fgetc()?
  3. What is EOF?
  4. Why is the result of fgetc() commonly stored in an int variable?
  5. What is the difference between fgetc() and fgets()?
  6. What is the purpose of fscanf()?
  7. Why should fopen() be checked for NULL?

Long Answer Questions

  1. Explain the process of reading from a file in C with a suitable program.
  2. Explain the use of fgetc() and EOF with a suitable example.
  3. Differentiate between fgetc(), fgets() and fscanf().
  4. Write a C program to read and display the contents of a text file.
🎥 Recommended Learning

Watch a beginner-friendly explanation of reading files in C.

▶ Watch: Reading Files in C — Hindi

📝 Handwritten Notes

A short handwritten-style revision sheet for reading from files will be provided here.

🧠 Mind Map

Use the mind map for file pointer, fgetc(), EOF, fgets(), fscanf() and fclose().