C File Management (CT 101): Complete IOE Notes on File I/O
An illustration representing C File Management concepts like fopen and fclose
File Management
4 hours | 5 marks

COMPUTER PROGRAMMING (CT 101) – Chapter 9

C File Management, or file handling, is the process of storing data in files on a disk for later use. This is crucial for creating persistent programs that can save their state, process large amounts of data, and interact with the operating system. C provides a comprehensive set of library functions in <stdio.h> to create, read, write, and manage files.

Chapter Information

Chapter 9: File Management (4 hours) – 5 marks

Course: Computer Programming (CT 101), I Year I Part

Description: This guide provides a complete overview of C File Management, covering text and binary files, file modes, I/O operations, random access, and error handling as per the IOE syllabus.

Credit: Sujan Karki

Detailed Chapter Notes

9.1 Binary and Text Files in C

  • Text Files: Store data as a sequence of human-readable characters. Special translations, like converting \n to a carriage return-line feed (CR-LF) on Windows, happen automatically. They are easy to create and read but less efficient for storing complex data.
  • Binary Files: Store data as a raw sequence of bytes, exactly as it is in the computer’s memory. They are not human-readable but are more efficient and compact for storing numbers, structures, and other non-textual data. No character translation occurs.

9.2 File Opening Modes

The fopen() function uses a mode string to determine how a file should be opened.

ModeMeaningAction if File ExistsAction if File Does Not Exist
"r"Read TextOpens for reading.Error (returns NULL).
"w"Write TextDeletes content.Creates a new file.
"a"Append TextOpens for writing at the end.Creates a new file.
"rb", "wb", "ab"Same as above, but for Binary files.
"r+"Read/Write TextOpens for reading and writing.Error (returns NULL).
"w+"Read/Write TextDeletes content.Creates a new file.
"a+"Read/Write TextOpens for reading and appending.Creates a new file.

9.3 Defining, Opening, and Closing a File

  1. Define a File Pointer: A special pointer of type FILE is needed to interact with a file.
    FILE *fp;
  2. Open the File: Use the fopen() function, which returns a FILE pointer on success or NULL on failure.
    fp = fopen("data.txt", "w");
  3. Close the File: Use the fclose() function to save changes and release the file. This is a crucial step.
    fclose(fp);

9.4 Input-Output Operations on Files

Character I/O (fgetc, fputc)

For reading/writing one character at a time.

  • fgetc(fp): Reads a character.
  • fputc(char, fp): Writes a character.

String I/O (fgets, fputs)

For reading/writing lines of text.

  • fgets(str, size, fp): Reads a line.
  • fputs(str, fp): Writes a string.

Formatted I/O (fscanf, fprintf)

Work like scanf and printf but for files.

  • fprintf(fp, "...", ...): Writes formatted data.
  • fscanf(fp, "...", ...): Reads formatted data.

Record I/O (fread, fwrite)

For reading/writing blocks of binary data, like structures.

  • fwrite(&var, size, n, fp): Writes n items of size from &var.
  • fread(&var, size, n, fp): Reads n items of size into &var.

9.5 Overview of Random File Access

Allows you to move the file pointer to any position in the file without reading sequentially.

  • ftell(fp): Returns the current position of the file pointer (in bytes from the start).
  • rewind(fp): Moves the file pointer back to the beginning of the file.
  • fseek(fp, offset, position): Moves the pointer.
    • offset: Number of bytes to move.
    • position: Can be SEEK_SET (from start), SEEK_CUR (from current position), or SEEK_END (from end).

9.6 Error Handling

It’s vital to check if a file was opened successfully. fopen() returns NULL if it fails. Always check for this to prevent your program from crashing.

FILE *fp;
fp = fopen("nonexistent.txt", "r");
if (fp == NULL) {
    printf("Error: Could not open file.\n");
    exit(1); // Terminate the program
}

Assignment Solution: Author Database Program

This program demonstrates creating a structure, writing multiple records to a binary file, and using fseek() for random access to read a specific record.

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

// Structure to hold author details
struct Author {
    char name[100];
    char nationality[50];
    int num_books;
};

int main() {
    FILE *fp;
    struct Author author;
    char choice;
    int record_num, total_records;

    fp = fopen("authors.dat", "ab+");

    if (fp == NULL) {
        printf("Error: Cannot open file.\n");
        exit(1);
    }

    do {
        printf("\n--- Enter New Author Details ---\n");
        while(getchar() != '\n'); // Clear input buffer
        
        printf("Enter author's name: ");
        fgets(author.name, sizeof(author.name), stdin);

        printf("Enter author's nationality: ");
        fgets(author.nationality, sizeof(author.nationality), stdin);

        printf("Enter number of books published: ");
        scanf("%d", &author.num_books);

        fwrite(&author, sizeof(struct Author), 1, fp);

        printf("\nAdd another record? (y/n): ");
        scanf(" %c", &choice);

    } while (choice == 'y' || choice == 'Y');

    printf("\n--- Retrieve a Specific Record ---\n");

    fseek(fp, 0, SEEK_END);
    total_records = ftell(fp) / sizeof(struct Author);
    printf("There are %d records in the file.\n", total_records);

    if (total_records > 0) {
        printf("Enter record number to display (1 to %d): ", total_records);
        scanf("%d", &record_num);

        if (record_num >= 1 && record_num <= total_records) {
            fseek(fp, (record_num - 1) * sizeof(struct Author), SEEK_SET);
            fread(&author, sizeof(struct Author), 1, fp);

            printf("\n--- Record #%d ---\n", record_num);
            printf("Author Name: %s", author.name);
            printf("Nationality: %s", author.nationality);
            printf("Books Published: %d\n", author.num_books);
        } else {
            printf("Error: Invalid record number.\n");
        }
    }

    fclose(fp);
    printf("\nFile closed.\n");

    return 0;
}

PDF Notes

×

Disclaimer

The educational materials provided on this website are intended as supplementary resources to support your learning journey. These study materials are sample documents designed to help students understand complex concepts in C Programming.

We have made every effort to ensure the accuracy of the content. However, we recommend students to refer to standard textbooks and consult with professors for authoritative explanations. These materials should be used as references only.

Scroll to Top