10 File Handling In C

C Programming · Unit 10 · 4 hrs

File Handling in C

Exam-focused notes for File Handling in C (C Programming, CSC115): what the TU syllabus asks and how it has actually been tested, with 8 solved past questions from this unit.

File Handling in C in short

This chapter covers how a C program stores data permanently in a file on disk: opening and closing a file, reading and writing it in different modes, moving around inside it, and handling the errors that file operations can produce.

File Handling in C: notes

Concept of File

A file is a collection of related data stored on a disk or other secondary storage device, which lets a program's data outlive the program itself and be read back whenever it is needed again. C represents an open file through a structure named FILE, defined in stdio.h, which records everything the library needs to know about the file, its name, its status, its buffer, its current position, and whether the end has been reached, all hidden from the programmer behind a file pointer:

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

The function fopen() establishes this connection, called opening the file, and returns a file pointer that every subsequent operation on that file uses.

Opening and Closing of File

A file is opened with fopen("filename", "mode"), where the mode string decides both how the file may be used and what happens if it does or does not already exist.

ModeMeaning
"r"open an existing file for reading only
"w"create for writing; erases existing content
"a"create for writing, or append to existing content
"r+"open an existing file for reading and writing
"w+"create for reading and writing; erases existing content
"a+"open for reading and appending
"rb", "wb", "ab", "rb+", "wb+", "ab+"the same six modes, opened in binary rather than text mode

What this unit covers

  • Concept of File
  • Opening and closing of File
  • Input Output Operations in File
  • Random access in File
  • Error Handling in Files

Opening and closing of File

2081 · 5 marks

Explain different file opening modes. [5]

When working with files in C, a file must be opened before any I/O operations can be performed on it. The fopen() function is used to open a file, and it requires a mode string that specifies how the file should be accessed. Syntax: --- Mode Name Description ------------------------- "r" Read Ope...

Open this answer on its own page →

Input Output Operations in File

2080 · 5 marks

Describe the different types of I/O functions used in file handling with syntax. [5]

File handling in C provides several categories of I/O functions to read from and write to files. These are defined in <stdio.h. --- Used to read/write a single character at a time. Writes a single character to a specified file and increments the file position pointer. Syntax: Example: fputc('A', ...

Open this answer on its own page →

2079 · 5 marks

Suppose a file named 'Num.txt' contains a list of integers. Write a program to extract the prime numbers only from that file and write them on 'Prime.txt' file. [5]

  • Read integers from Num.txt using fscanf() - Check each integer for primality using a loop - Write prime numbers to Prime.txt using fprintf() - Use FILE pointer and formatted I/O --- --- Step Description ------------------- fopen("Num.txt", "r") Opens Num.txt in read mode; returns FILE pointer f...
Open this answer on its own page →

2078 · 5 marks

Write a program that simply reads data from a file. [5]

To read data from a file in C, the following steps are performed: 1. Declare a file pointer of type FILE 2. Open the file using fopen() in read mode "r" 3. Read data from the file using file input functions (e.g., fgetc(), fscanf(), fgets()) 4. Close the file using fclose() after reading is compl...

Open this answer on its own page →

2077 · 5 marks

Explain different file I/O functions with example. [5]

File I/O functions allow a C program to read data from and write data to files stored on disk. These functions are declared in the header file <stdio.h. --- These functions read or write one character at a time. Writes a single character to a specified file and increments the file position pointe...

Open this answer on its own page →

2074 · 5 marks

Write a program to read and print data stored in a file input.txt. [5]

  • A file is a collection of related data placed on disk. - fopen() is used to open a file with a specified mode. - Mode "r" opens an existing file for reading only; previous data is not erased. - fgetc() reads a single character from a file and increments the file pointer. - fclose() is used to c...
Open this answer on its own page →

Concept of File

2075 · 10 marks

Why do we need data files?What are the different file opening modes?Write a program that reads data from a file "input.txt" and writes to "output.txt" file.[2+3+5]

Show solved answer

Data Files, File Opening Modes, and File Copy Program


(a) Why Do We Need Data Files?

When a program runs, all data is stored in main memory (RAM), which is volatile -- it is lost when the program ends or the computer is switched off. Data files solve this problem by providing permanent storage on secondary storage devices (hard disk, etc.).

Reasons we need data files:

  • Persistence: Data stored in files remains even after the program terminates.
  • Large data handling: Files allow processing of data too large to fit in memory at once.
  • Data sharing: Multiple programs can read from and write to the same file.
  • Reusability: Data entered once can be reused many times without re-entering.
  • Record keeping: Files allow maintaining logs, reports, and databases permanently.

(b) Different File Opening Modes

As per the notes, the file opening modes used in C are:

ModeDescription
"r"Open existing file for reading only. File must exist. Previous data is not erased.
"w"Open file for writing. Creates new file if it does not exist. Erases existing data if file exists.
"a"Open file for appending. Creates new file if it does not exist. New data is added at the end; existing data is not erased.
"r+"Open existing file for reading and writing (update mode). File must exist. Data is not erased.
"w+"Open file for writing and reading. Creates new file if not exists. Erases existing data if file exists.
"a+"Open file for appending and reading. Creates new file if not exists. Cannot modify existing data.
"rb"Open binary file for reading.
"wb"Open binary file for writing.
"ab"Open binary file for appending.
"rb+"Open binary file for reading and writing.
"wb+"Create binary file for reading and writing.
"ab+"Open binary file for appending and reading.

(c) Program to Read from "input.txt" and Write to "output.txt"

Approach:

  • Open input.txt in "r" (read) mode.
  • Open output.txt in "w" (write) mode.
  • Read characters one by one from input.txt using fgetc().
  • Write each character to output.txt using fputc().
  • Close both files after the operation.
#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *fp_in, *fp_out;
    char ch;

    /* Open input.txt for reading */
    fp_in = fopen("input.txt", "r");
    if (fp_in == NULL)
    {
        printf("Error: Cannot open input.txt\n");
        exit(1);
    }

    /* Open output.txt for writing */
    fp_out = fopen("output.txt", "w");
    if (fp_out == NULL)
    {
        printf("Error: Cannot open output.txt\n");
        fclose(fp_in);
        exit(1);
    }

    /* Read from input.txt and write to output.txt character by character */
    while ((ch = fgetc(fp_in)) != EOF)
    {
        fputc(ch, fp_out);
    }

    printf("Data successfully copied from input.txt to output.txt\n");

    /* Close both files */
    fclose(fp_in);
    fclose(fp_out);

    return 0;
}

Explanation of Key Steps:

StepCodePurpose
Open input filefopen("input.txt", "r")Opens file for reading
Open output filefopen("output.txt", "w")Opens/creates file for writing
NULL checkif (fp_in == NULL)Checks if file opened successfully
Read characterfgetc(fp_in)Reads one character from input file and advances file pointer
Write characterfputc(ch, fp_out)Writes one character to output file
EOF check!= EOFStops reading when end of file is reached
Close filesfclose()Releases file resources

Sample Output:

Data successfully copied from input.txt to output.txt

The contents of input.txt will be completely copied into output.txt.

Open this answer on its own page →

2075 · 5 marks

Write short note on: a. Benefits of data files b. Graphics functions. [2.5+2.5]

Show solved answer

Short Notes


a. Benefits of Data Files (2.5 marks)

A file is a collection of related data placed on the disk. C supports the concept of files through which data can be stored on a disk or secondary storage device, and the stored data can be read whenever required.

The key benefits of using data files are:

1. Permanent Storage of Data

Data stored in files is saved on the disk (secondary storage). Unlike variables stored in RAM, file data is not lost when the program terminates. It can be retrieved at any time.

2. Handling Large Amounts of Data

Files allow programs to process large volumes of data that cannot be held entirely in memory at once. Data can be read or written in parts (blocks, strings, characters, etc.).

3. Data Reusability

Once data is written to a file, it can be read and reused by the same program or different programs multiple times without re-entering the data.

4. Data Sharing Between Programs

Multiple programs can access the same data file, enabling easy sharing and transfer of information between different applications.

5. Easy Data Modification

Files can be opened in various modes such as "r+" (read + write / update mode) or "a+" (append + read) to modify or add new data without destroying existing data.

6. Organized Data Management

Data can be stored in a structured and organized manner. C provides various file modes ("r", "w", "a", "rb", "wb", etc.) and I/O functions (fread(), fwrite(), fprintf(), fscanf(), etc.) to manage data efficiently.

7. Buffered I/O for Efficiency

C file handling uses buffers to temporarily hold data during read/write operations. When a file is closed using fclose(), all buffered data is flushed (written) to the file, ensuring no data is lost and improving I/O performance.


b. Graphics Functions (2.5 marks)

C provides a graphics library (graphics.h) that allows drawing shapes, lines, and images on the screen using pixel-based coordinates. The origin pixel (0, 0) is located at the top-left corner of the screen.

The important graphics functions are:

1. initgraph(&gd, &gm, path)

  • Purpose: Initializes the graphics system and puts the screen into graphics mode.
  • gd = graphics driver, gm = graphics mode, path = path to BGI driver files.
  • Example: initgraph(&gd, &gm, "c:\\tc\\bgi");

2. circle(x, y, radius)

  • Purpose: Draws a circle with center at (x, y) and the given radius.
  • Example: circle(300, 200, 150);

3. line(x1, y1, x2, y2)

  • Purpose: Draws a line from point (x1, y1) to point (x2, y2) using pixels placed near each other.
  • Coordinates are measured from the top-left corner of the screen.

4. getpixel(x, y)

  • Purpose: Gets the color of the pixel at position (x, y).
  • Returns an integer value corresponding to the color of that pixel.
  • The pixel is the smallest element on the graphics display screen.

5. setcolor(color)

  • Purpose: Sets the current drawing color for subsequent graphics operations.
  • Example: setcolor(WHITE);

6. closegraph()

  • Purpose: Closes the graphics mode and restores the screen to text mode, freeing resources used by the graphics system.

Example Program (from notes):

#include<stdio.h>
#include<conio.h>
#include<graphics.h>
void main()
{
    int gd = DETECT, gm;
    initgraph(&gd, &gm, "c:\\tc\\bgi");
    circle(300, 200, 150);
    setcolor(WHITE);
    getch();
    closegraph();
}

Note: In C graphics, images are formed by placing pixels (dots) near each other on the screen. The pixel at position (0, 0) is always at the top-left corner of the screen.

Open this answer on its own page →