C Programming · Unit 10
File Input Output and Preprocessor
Exam-focused notes for File Input Output and Preprocessor (C Programming, BIT102): what the TU syllabus asks and how it has actually been tested, with 14 solved past questions from this unit.
File Input Output and Preprocessor in short
This chapter shows how programs save data in files and how the preprocessor prepares code before compilation. Files keep data after the program ends.
What this unit covers
- File handling and file operations
- File opening modes
- Fwrite and fread functions
- Fgets and fgetc functions
- Formatted input output
- Unformatted input output
- File creation and copying
- Merging files
- Reading and writing numbers to files
- Preprocessor directives
- Macros and macro vs function
- File inclusion
File handling and file operations
2081 · 5 marks
Write a program to write N numbers in file "number.txt" and then read it and display only even numbers. [5]
Show solved answerHide answer
Program: Write N Numbers to File and Display Even Numbers
C Program
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
int i, n, num;
// Step 1: Get N from user
printf("Enter how many numbers to write: ");
scanf("%d", &n);
// Step 2: Open file for writing
fp = fopen("number.txt", "w");
if (fp == NULL) {
printf("Error opening file for writing!\n");
exit(1);
}
// Step 3: Write N numbers to file
printf("Enter %d numbers:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &num);
fprintf(fp, "%d\n", num);
}
fclose(fp);
printf("Numbers written to file successfully.\n");
// Step 4: Open file for reading
fp = fopen("number.txt", "r");
if (fp == NULL) {
printf("Error opening file for reading!\n");
exit(1);
}
// Step 5: Read and display only even numbers
printf("\nEven numbers from file:\n");
while (fscanf(fp, "%d", &num) != EOF) {
if (num % 2 == 0) {
printf("%d\n", num);
}
}
fclose(fp);
return 0;
}
Sample Output
Enter how many numbers to write: 6
Enter 6 numbers:
3 8 15 22 7 10
Numbers written to file successfully.
Even numbers from file:
8
22
10
Key Points
| Step | Operation | Function Used |
|---|---|---|
| 1 | Open file for writing | fopen("number.txt", "w") |
| 2 | Write numbers to file | fprintf(fp, "%d\n", num) |
| 3 | Close file after writing | fclose(fp) |
| 4 | Open file for reading | fopen("number.txt", "r") |
| 5 | Read numbers from file | fscanf(fp, "%d", &num) |
| 6 | Check even condition | num % 2 == 0 |
Note: Always check if
fopen()returnsNULLto handle file errors, and always callfclose()after file operations to release resources.
2080 · 5 marks
Why data file is needed? Write a program to write N numbers in file 'number.txt' and then read it and display only even numbers. [5]
Preprocessor directives
2080 · 5 marks
Write short notes on: a) Macro Write short notes on: b) Opening and closing file [2.5+2.5]
Show solved answerHide answer
Short Notes
a) Macro
A macro is a preprocessor directive in C that allows a name (identifier) to be associated with a piece of code, a constant, or an expression. The C preprocessor replaces every occurrence of the macro name with its defined text before actual compilation begins.
Types of Macros
1. Object-like Macro (Simple/Symbolic Constant)
#define PI 3.14159
#define MAX 100
Every occurrence of PI in the code is replaced by 3.14159.
2. Function-like Macro (Macro with Arguments)
#define SQUARE(x) ((x)*(x))
#define MAX(a,b) ((a)>(b) ? (a) : (b))
Usage: SQUARE(5) is replaced by ((5)*(5)) = 25.
Key Points
- Defined using
#definedirective. - Processed by the preprocessor, not the compiler.
- No type checking is performed (unlike functions).
- Parentheses should be used carefully to avoid operator precedence errors.
- Macros can be undefined using
#undef. - They make code more readable, portable, and easy to maintain.
b) Opening and Closing a File
In C, file handling is done using the standard library <stdio.h>. Before reading from or writing to a file, it must be opened, and after operations are complete, it must be closed.
Opening a File
The fopen() function is used to open a file.
Syntax:
FILE *fptr;
fptr = fopen("filename", "mode");
FILE *is a pointer to a file structure.- If the file cannot be opened,
fopen()returnsNULL.
File Opening Modes
| Mode | Description |
|---|---|
"r" | Open for reading (file must exist) |
"w" | Open for writing (creates new or truncates existing) |
"a" | Open for appending (creates if not exists) |
"r+" | Open for both reading and writing |
"w+" | Open for reading and writing (truncates) |
"a+" | Open for reading and appending |
Closing a File
The fclose() function is used to close an opened file.
Syntax:
fclose(fptr);
- It flushes any unwritten data to the file.
- Releases the file pointer resource.
- Returns
0on success,EOFon failure.
Example
#include <stdio.h>
int main() {
FILE *fptr;
fptr = fopen("data.txt", "w"); // Open file for writing
if (fptr == NULL) {
printf("Error opening file!\n");
return 1;
}
fprintf(fptr, "Hello, File!\n"); // Write to file
fclose(fptr); // Close the file
return 0;
}
Note: Always check if
fopen()returnsNULLbefore performing file operations, and always close the file after use to prevent data loss or resource leaks.
2081.2 · 5 marks
Define pre-processor. How do you pass pointer as argument? [5]
Show solved answerHide answer
Pre-processor and Passing Pointer as Argument
Pre-processor
A pre-processor is a program (or phase of compilation) that processes the source code before it is passed to the compiler. It handles directives that begin with the # symbol.
Key features:
- It performs text substitution and file inclusion
- It does not understand C syntax; it works purely on text
- Pre-processor directives are not C statements (no semicolon needed)
Common pre-processor directives:
| Directive | Purpose |
|---|---|
#include | Includes header/source files |
#define | Defines macros/constants |
#undef | Undefines a macro |
#ifdef / #ifndef | Conditional compilation |
#endif | Ends conditional block |
Example:
#include <stdio.h>
#define PI 3.14159
Passing Pointer as Argument
When a pointer is passed as an argument to a function, the function receives the address of the variable. This allows the function to directly modify the original variable (call by reference).
Syntax
return_type function_name(data_type *pointer_parameter);
How it works
- Declare a variable and obtain its address using
& - Pass the address to the function
- Inside the function, use
*(dereference operator) to access/modify the value
Example: Swap two numbers using pointers
#include <stdio.h>
// Function that accepts pointers as arguments
void swap(int *a, int *b) {
int temp;
temp = *a; // store value at address a
*a = *b; // assign value at b to address a
*b = temp; // assign temp to address b
}
int main() {
int x = 10, y = 20;
printf("Before swap: x = %d, y = %d\n", x, y);
swap(&x, &y); // passing addresses of x and y
printf("After swap: x = %d, y = %d\n", x, y);
return 0;
}
Output
Before swap: x = 10, y = 20
After swap: x = 20, y = 10
Key Points
&xpasses the address ofxto the function*ainside the function dereferences the pointer to access the actual value- Changes made inside the function reflect in the original variables
- This is the basis of call by reference in C
Note: Passing pointers as arguments is more efficient for large data structures (like arrays and structures) since it avoids copying the entire data.
File creation and copying
2079 · 10 marks
List the advantages and disadvantages of global variable. Assume the two data files "numl.txt" and "num2.txt" containing integers. Merge these two files to the third file named " file3.txt". Here, the integers of " file3.t-xt" must be written in sorted order.[10]
Show solved answerHide answer
Global Variables & File Merging Program
Part A: Advantages and Disadvantages of Global Variables
A global variable is a variable declared outside all functions, making it accessible to every function in the program.
Advantages
| # | Advantage | Explanation |
|---|---|---|
| 1 | Universal Accessibility | Any function can read or modify the variable without receiving it as a parameter |
| 2 | Reduced Parameter Passing | Function signatures stay simple; no need to pass shared data repeatedly |
| 3 | Easy Data Sharing | Multiple functions can communicate through a common variable |
| 4 | Persistence | The variable retains its value for the entire lifetime of the program |
| 5 | Convenient for Constants | Useful for program-wide constants or configuration values |
Disadvantages
| # | Disadvantage | Explanation |
|---|---|---|
| 1 | Uncontrolled Access | Any function can accidentally overwrite the value, causing hard-to-find bugs |
| 2 | Namespace Pollution | Large programs with many globals risk naming conflicts |
| 3 | Reduced Modularity | Functions depend on external state, making them difficult to reuse |
| 4 | Violates Data Hiding | All data is exposed, breaking the principle of encapsulation |
| 5 | Difficult Debugging | Tracking which function changed the value requires checking the entire program |
Part B: Merge Two Files into a Third File in Sorted Order
Logic / Algorithm
1. Open num1.txt and read all integers into array a[]
2. Open num2.txt and read all integers into array b[]
3. Copy both arrays into a combined array c[]
4. Sort c[] using Bubble Sort (ascending order)
5. Open file3.txt for writing
6. Write every element of sorted c[] into file3.txt
7. Close all files
Complete C Program
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *f1, *f2, *f3;
int a[100], b[100], c[200];
int n1 = 0, n2 = 0;
int i, j, k = 0, temp;
/* ---- Step 1: Read integers from num1.txt ---- */
f1 = fopen("num1.txt", "r");
if (f1 == NULL)
{
printf("Error: Cannot open num1.txt\n");
exit(1);
}
while (fscanf(f1, "%d", &a[n1]) != EOF)
{
n1++;
}
fclose(f1);
/* ---- Step 2: Read integers from num2.txt ---- */
f2 = fopen("num2.txt", "r");
if (f2 == NULL)
{
printf("Error: Cannot open num2.txt\n");
exit(1);
}
while (fscanf(f2, "%d", &b[n2]) != EOF)
{
n2++;
}
fclose(f2);
/* ---- Step 3: Combine both arrays into c[] ---- */
for (i = 0; i < n1; i++)
c[k++] = a[i];
for (i = 0; i < n2; i++)
c[k++] = b[i];
/* ---- Step 4: Sort c[] using Bubble Sort ---- */
for (i = 0; i < k - 1; i++)
{
for (j = 0; j < k - i - 1; j++)
{
if (c[j] > c[j + 1])
{
/* Swap */
temp = c[j];
c[j] = c[j + 1];
c[j + 1] = temp;
}
}
}
/* ---- Step 5: Write sorted integers to file3.txt ---- */
f3 = fopen("file3.txt", "w");
if (f3 == NULL)
{
printf("Error: Cannot open file3.txt\n");
exit(1);
}
for (i = 0; i < k; i++)
{
fprintf(f3, "%d\n", c[i]);
}
fclose(f3);
printf("Merged and sorted successfully into file3.txt\n");
return 0;
}
Dry Run Example
num1.txt contains: 5 2 8
num2.txt contains: 3 1 7
| Step | Array State |
|---|---|
| After reading | a[] = {5, 2, 8}, b[] = {3, 1, 7} |
| After combining | c[] = {5, 2, 8, 3, 1, 7} |
| After Bubble Sort | c[] = {1, 2, 3, 5, 7, 8} |
| Written to file3.txt | 1 2 3 5 7 8 (one per line) |
Key File Handling Functions Used
| Function | Purpose |
|---|---|
fopen(name, "r") | Open file for reading |
fopen(name, "w") | Open file for writing |
fscanf(fp, "%d", &x) | Read an integer from file |
fprintf(fp, "%d\n", x) | Write an integer to file |
fclose(fp) | Close the file and flush buffer |
exit(1) | Terminate program on error |
Conclusion
Global variables simplify data sharing but reduce modularity and security, so they should be used carefully. The file merging program demonstrates practical use of fopen(), fscanf(), fprintf() and fclose(), while the bubble sort applied to the combined array guarantees that every integer read from num1.txt and num2.txt is written into file3.txt in ascending order.
2078 · 5 marks
Write a program to create a file "duplicate" that contains the exact copy of file "original". [5]
File inclusion
2079 · 5 marks
How do you include a file to another file? Illustrate with an example. [5]
Macros and macro vs function
2079 · 5 marks
Write short notes on: a) Macro vs Function Write short notes on: b) Break vs Continue [2.5+2.5]
2077 · 5 marks
Write short notes on: a) Macros Write short notes on: b) Null Pointers [2.5+2.5]
Formatted input output
2078 · 5 marks
Explain any four input/output functions used in C language with suitable example [5]
0 · 5 marks
Write short notes on: i) Formatted input/output Write short notes on: ii) C Preprocessors/directives [2.5+2.5]
File opening modes
2077 · 5 marks
Why file is used in programming? Explain different file opening modes. [5]
Fgets and fgetc functions
2081.2 · 10 marks
Differentiate between fgets() and fgetc(). What is the task of typedef? Write a program to define a structure Book with data members name, price and author. Display the names of the book having price greater than 1000.[10]
Fwrite and fread functions
0 · 5 marks
Explain the syntax of fwrite() function. Write a program to create a file named "student.txt" and stores record of any five students given by user. [5]
Make Unit 10 stick
Practice BIT102 with flashcards & quizzes