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.
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
Input Output Operations in File
2080 · 5 marks
Describe the different types of I/O functions used in file handling with syntax. [5]
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]
2078 · 5 marks
Write a program that simply reads data from a file. [5]
2077 · 5 marks
Explain different file I/O functions with example. [5]
2074 · 5 marks
Write a program to read and print data stored in a file input.txt. [5]
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 answerHide 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:
| Mode | Description |
|---|---|
"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.txtin"r"(read) mode. - Open
output.txtin"w"(write) mode. - Read characters one by one from
input.txtusingfgetc(). - Write each character to
output.txtusingfputc(). - 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:
| Step | Code | Purpose |
|---|---|---|
| Open input file | fopen("input.txt", "r") | Opens file for reading |
| Open output file | fopen("output.txt", "w") | Opens/creates file for writing |
| NULL check | if (fp_in == NULL) | Checks if file opened successfully |
| Read character | fgetc(fp_in) | Reads one character from input file and advances file pointer |
| Write character | fputc(ch, fp_out) | Writes one character to output file |
| EOF check | != EOF | Stops reading when end of file is reached |
| Close files | fclose() | 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.
2075 · 5 marks
Write short note on: a. Benefits of data files b. Graphics functions. [2.5+2.5]
Show solved answerHide 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.
Make Unit 10 stick
Practice CSC115 with flashcards & quizzes