File Handling in C

Subject: Data Structures and Algorithms · Language: C · Level: intermediate · 6 min read

Read, write, append, and close files using FILE pointers, fopen, fprintf, fgets, fscanf, and fclose.

File handling allows a C program to store data permanently. Normally, values stored in variables are lost when the program ends. A file lets the program save data and read it again later.

This is why file handling is important in real applications. Student records, bills, logs, reports, settings, and saved results are commonly stored in files.

Why File Handling Is Needed

Without files, a program can only work with temporary data. Once the program closes, the data disappears from memory.

With files, the program can write data to disk. Later, the same program or another program can open that file and read the stored information.

For example, a marks management program can save a student's name and marks in a file. The next time the teacher opens the program, the data can be loaded again.

File Pointer

C uses a `FILE *` pointer to work with files. This pointer does not store the file content directly. It stores information that helps C communicate with the opened file.

```c

FILE *file;

```

You can think of a file pointer as a connection between your C program and the file on disk.

Opening a File

`fopen` opens a file and returns a file pointer.

```c

FILE *file = fopen("notes.txt", "w");

```

The first argument is the file name. The second argument is the mode, which tells C whether you want to read, write, append, or do both reading and writing.

If the file cannot be opened, `fopen` returns `NULL`. Always check this before reading or writing.

Common File Modes

The most important beginner warning is about `w` mode: it clears old file content. Use it only when you really want to replace the file.

Text File and Binary File

A text file stores data in readable characters. A binary file stores data in raw binary form.

Beginner file handling usually starts with text files because they are easier to open and inspect.

Text files are good for simple records and reports. Binary files are used when data must be stored exactly as it appears in memory, such as structures, images, or compiled data.

Writing to a File

`fprintf` writes formatted data into a file, similar to how `printf` writes to the screen.

The difference is simple: `printf` prints on the screen, while `fprintf` writes into a file.

Reading from a File

C provides different functions for reading file data.

`fgets` is often safer for reading lines because it can read spaces also. For example, a student name like Rahul Kumar has a space, and `fscanf` with `%s` would read only Rahul.

Complete File Handling Program

This program writes a student record into a file, closes it, opens the same file again, and reads the data back.

```c

#include <stdio.h>

int main(void) {

FILE *file;

char name[] = "Rahul";

int marks = 86;

file = fopen("student.txt", "w");

if (file == NULL) {

printf("Unable to open file for writing\n");

return 1;

}

fprintf(file, "Name: %s\n", name);

fprintf(file, "Marks: %d\n", marks);

fclose(file);

printf("Student record saved successfully\n");

file = fopen("student.txt", "r");

if (file == NULL) {

printf("Unable to open file for reading\n");

return 1;

}

char line[100];

printf("Reading from file:\n");

while (fgets(line, sizeof(line), file) != NULL) {

printf("%s", line);

}

fclose(file);

return 0;

}

```

Closing a File

`fclose` closes the file. Closing is important because it saves pending data and releases file resources.

If a program opens many files and does not close them, it can waste system resources or behave incorrectly.

File Handling Flow

Most file programs follow this order: open the file, check whether it opened successfully, read or write data, then close the file.

Skipping the check after `fopen` can cause errors if the file path is wrong or permission is denied.

Append Mode

Append mode is used when you do not want to erase old data. It adds new data at the end of the file.

For example, a log file should usually use append mode because every new log entry should be added after old entries.

File Path Note

If you write only `student.txt`, the file is created in the program's current working directory. If you give a full path, C tries to use that exact location.

Path mistakes are common in file handling, so when a file does not open, check the file name, folder location, and permission.

Important Points

Practice Question

Write a C program that stores a student's name and marks in a file, then reads the same file and prints the data.

More C Lessons

Browse all PrepCampus study materials