File Management in C

File Management in C enables programs to store and retrieve data persistently on secondary storage devices (such as Hard Disks and SSDs). While ordinary variables and arrays vanish as soon as a program terminates (volatile RAM storage), files preserve records, logs, and user configurations permanently.

Streams and the FILE Pointer in C

In C programming, all file operations are handled through a predefined structure named FILE defined in the <stdio.h> header. A file pointer (FILE *fp;) points to a memory buffer containing control information about the file (such as its current position, state, and permissions).

File Opening Modes in C

Files are opened using the fopen() library function with specific mode flags:

Mode

Meaning & Behavior

If File Does Not Exist

"r"

Opens an existing text file for reading.

Returns NULL

"w"

Opens a text file for writing. Overwrites existing contents!

Creates a new file

"a"

Opens for appending data to the end of the file.

Creates a new file

"r+"

Opens for both reading and writing.

Returns NULL

"w+"

Opens for reading and writing (truncates existing file to 0 bytes).

Creates a new file

"a+"

Opens for reading and appending without overwriting.

Creates a new file

"rb", "wb"

Opens binary files for reading or writing bytes directly.

Standard binary rules

Standard File Handling Functions in C

 fopen(filename, mode): Opens a file and returns a FILE* pointer, or NULL if an error occurs.

 fclose(fp): Flushes any buffered data and releases system resources associated with the stream.

 fgetc(fp) / fputc(char, fp): Reads or writes a single character.

 fgets(str, n, fp) / fputs(str, fp): Reads or writes an entire line of text safely.

 fprintf(fp, format, ...) / fscanf(fp, format, ...): Formatted input and output identical to printf/scanf, but targeted to a file stream.

 fread() / fwrite(): Read or write binary blocks (such as entire C structures).

Robust Working Example: Writing and Reading a Text File

This complete, standard-compliant C program safely creates a file, writes user input, closes it, and reads it back character by character:


#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *fp;
    int ch;

    /* 1. Open file for writing */
    fp = fopen("demo.txt", "w");
    if(fp == NULL) {
        printf("Error: Unable to create file!\n");
        return 1;
    }

    printf("Enter text to write into file (Press CTRL+D on Linux or CTRL+Z then Enter on Windows to stop):\n");
    while((ch = getchar()) != EOF) {
        fputc(ch, fp);
    }
    fclose(fp); /* Close write stream */

    /* 2. Open file for reading */
    fp = fopen("demo.txt", "r");
    if(fp == NULL) {
        printf("Error: Unable to open file for reading!\n");
        return 1;
    }

    printf("\n--- Contents of demo.txt ---\n");
    while((ch = fgetc(fp)) != EOF) {
        putchar(ch);
    }
    fclose(fp); /* Close read stream */

    return 0;
}
							

Random Access in Files: fseek(), ftell(), and rewind()

Rather than reading sequentially from start to end, C allows you to jump directly to any byte in a file:

 ftell(fp): Returns the current position of the file pointer (byte offset from beginning).

 rewind(fp): Resets the file pointer back to the beginning of the file (equivalent to fseek(fp, 0, SEEK_SET);).

 fseek(fp, offset, origin): Moves the position indicator using three constants:


fseek(fp, 0, SEEK_SET);   /* Move to beginning of file */
fseek(fp, 10, SEEK_CUR);  /* Move 10 bytes forward from current position */
fseek(fp, -5, SEEK_END);  /* Move 5 bytes back from end of file */
							

Practice Session for Beginner Students

Test your file handling skills with these output exercises, MCQs, and real-world BCA lab tasks.

Part 1: Spot the Bug & Predict the Output

Problem 1: What is dangerous about the following code?


FILE *fp = fopen("data.txt", "r");
char ch = fgetc(fp);
							

Answer & Explanation: Two major flaws: (1) The code never checks if fp == NULL. If data.txt doesn't exist, passing NULL into fgetc crashes the program with a Segmentation Fault; (2) ch is declared as char instead of int. EOF is an integer (usually -1). On systems where char is unsigned, ch == EOF will never be true, resulting in an infinite loop.

Part 2: Multiple Choice Questions (BCA Exam Preparation)

Q1. What value does fopen() return if it fails to open a requested file?
A) -1
B) 0
C) NULL
D) EOF
Correct Answer: C) NULL.

Q2. Which mode is used to append text to an existing file without deleting its prior content?
A) "w"
B) "r"
C) "a"
D) "w+"
Correct Answer: C) "a" (Append mode).

Q3. What does the rewind() function do?
A) Closes and reopens the file
B) Sets the file position to the beginning of the file
C) Deletes the file
D) Moves to the end of the file
Correct Answer: B) Sets the file position to the beginning of the file.

Part 3: Hands-on Lab Assignments for Beginners

Assignment 1: Write a C program to copy the contents of one text file (source.txt) to another (target.txt).
Logic Hint: Open source.txt in "r" mode and target.txt in "w" mode. Loop with while((ch = fgetc(f1)) != EOF) fputc(ch, f2);.

Assignment 2: Write a program to count the number of characters, words, and lines in a given text file.
Logic Hint: Increment characters on every byte, increment lines whenever ch == '\n', and count words whenever whitespace follows a word.

Part 4: Frequently Asked University Viva Questions

1. What is the difference between text files and binary files?
Answer: Text files store plain ASCII/UTF characters with newline translations (`\r\n` vs `\n`). Binary files store raw bytes exactly as they appear in memory without translation, making them faster and more compact for structures and numbers.

2. Why is it mandatory to call fclose()?
Answer: fclose() flushes any unsaved data residing in the I/O buffer to the disk, prevents memory leaks, and releases the file lock back to the operating system.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!