10 File Input Output And Preprocessor

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.

File Input Output and Preprocessor: notes

File handling and file operations

A file is a named place on disk that stores data permanently. In C, files are handled through a pointer of type FILE *, defined in <stdio.h>.

The basic operations are:

  • Open the file with fopen().
  • Read or write data.
  • Close the file with fclose().
FILE *fp = fopen("data.txt", "r");
if (fp == NULL) {
    printf("Cannot open file\n");
    return 1;
}
/* work with the file */
fclose(fp);

fopen returns NULL when it fails, so always check it. Closing a file saves buffered data and frees resources. Other useful functions are feof(), rewind(), fseek(), ftell() and remove().

File opening modes

ModeMeaning
rRead. File must exist.
wWrite. Creates a new file or erases an old one.
aAppend. Adds data at the end. Creates the file if missing.
r+Read and write. File must exist.
w+Read and write. Erases existing content.
a+Read and append
rb, wb, abSame as above, for binary files.

Mode w destroys old data, so use it with care. Add b for binary data, such as structures written with fwrite.

Fwrite and fread functions

fwrite and fread handle blocks of binary data, such as arrays and structures.

size_t fwrite(const void *ptr, size_t size, size_t count, FILE *fp);
size_t fread(void *ptr, size_t size, size_t count, FILE *fp);
struct student { int roll; char name[20]; float marks; };
struct student s = {1, "Hari", 75.5f}, t;

FILE *fp = fopen("stu.dat", "wb");
fwrite(&s, sizeof(s), 1, fp);
fclose(fp);

fp = fopen("stu.dat", "rb");
fread(&t, sizeof(t), 1, fp);
printf("%d %s %.1f\n", t.roll, t.name, t.marks);
fclose(fp);

Both return the number of items processed. A file written this way is not readable in a text editor.

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 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

StepOperationFunction Used
1Open file for writingfopen("number.txt", "w")
2Write numbers to filefprintf(fp, "%d\n", num)
3Close file after writingfclose(fp)
4Open file for readingfopen("number.txt", "r")
5Read numbers from filefscanf(fp, "%d", &num)
6Check even conditionnum % 2 == 0

Note: Always check if fopen() returns NULL to handle file errors, and always call fclose() after file operations to release resources.

Open this answer on its own page →

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]

Data files are needed for the following reasons: 1. Permanent Storage - Data stored in variables is lost when the program ends. Files store data permanently on disk. 2. Large Data Handling - Files allow storing and processing large amounts of data that cannot fit in memory at once. 3. Data Sharin...

Open this answer on its own page →

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 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 #define directive.
  • 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() returns NULL.

File Opening Modes

ModeDescription
"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 0 on success, EOF on 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() returns NULL before performing file operations, and always close the file after use to prevent data loss or resource leaks.

Open this answer on its own page →

2081.2 · 5 marks

Define pre-processor. How do you pass pointer as argument? [5]

Show solved 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:

DirectivePurpose
#includeIncludes header/source files
#defineDefines macros/constants
#undefUndefines a macro
#ifdef / #ifndefConditional compilation
#endifEnds 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

  1. Declare a variable and obtain its address using &
  2. Pass the address to the function
  3. 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

  • &x passes the address of x to the function
  • *a inside 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.

Open this answer on its own page →

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 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

#AdvantageExplanation
1Universal AccessibilityAny function can read or modify the variable without receiving it as a parameter
2Reduced Parameter PassingFunction signatures stay simple; no need to pass shared data repeatedly
3Easy Data SharingMultiple functions can communicate through a common variable
4PersistenceThe variable retains its value for the entire lifetime of the program
5Convenient for ConstantsUseful for program-wide constants or configuration values

Disadvantages

#DisadvantageExplanation
1Uncontrolled AccessAny function can accidentally overwrite the value, causing hard-to-find bugs
2Namespace PollutionLarge programs with many globals risk naming conflicts
3Reduced ModularityFunctions depend on external state, making them difficult to reuse
4Violates Data HidingAll data is exposed, breaking the principle of encapsulation
5Difficult DebuggingTracking 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

StepArray State
After readinga[] = {5, 2, 8}, b[] = {3, 1, 7}
After combiningc[] = {5, 2, 8, 3, 1, 7}
After Bubble Sortc[] = {1, 2, 3, 5, 7, 8}
Written to file3.txt1 2 3 5 7 8 (one per line)

Key File Handling Functions Used

FunctionPurpose
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.

Open this answer on its own page →

2078 · 5 marks

Write a program to create a file "duplicate" that contains the exact copy of file "original". [5]

--- Step Description ------------------- fopen("original", "r") Opens the source file "original" in read mode fopen("duplicate", "w") Creates/opens the destination file "duplicate" in write mode NULL check Verifies files opened successfully; exits with error if not fgetc(original) Reads one chara...

Open this answer on its own page →

File inclusion

2079 · 5 marks

How do you include a file to another file? Illustrate with an example. [5]

In C programming, the include preprocessor directive is used to include the contents of one file into another file. This is handled by the C preprocessor before actual compilation begins. When the preprocessor encounters include, it replaces that line with the entire contents of the specified fil...

Open this answer on its own page →

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]

Feature Macro Function --------- Definition Defined using define preprocessor directive Defined using return type, name, and body Processing Handled by preprocessor (before compilation) Handled by compiler at compile/run time Execution Inline substitution (code is pasted at each call site) Contro...

Open this answer on its own page →

2077 · 5 marks

Write short notes on: a) Macros Write short notes on: b) Null Pointers [2.5+2.5]

A macro is a preprocessor directive in C that allows the programmer to define symbolic names or constants and to create inline code substitutions before the actual compilation begins. Macros are processed by the C preprocessor using the define directive. 1. Object-like Macros (Simple Constants) E...

Open this answer on its own page →

Formatted input output

2078 · 5 marks

Explain any four input/output functions used in C language with suitable example [5]

--- C language provides several built-in I/O functions through the header file <stdio.h (Standard Input/Output Header). --- Used to display/print output to the standard output (screen). Syntax: Example: Output: My age is 20 --- Used to read/accept input from the standard input (keyboard). Syntax:...

Open this answer on its own page →

0 · 5 marks

Write short notes on: i) Formatted input/output Write short notes on: ii) C Preprocessors/directives [2.5+2.5]

Formatted input/output in C refers to reading and writing data in a specific format using standard library functions defined in <stdio.h. Used to display formatted output to the standard output (screen). Syntax: Format Specifiers: Specifier Meaning -------------------- %d Integer %f Float %c Char...

Open this answer on its own page →

File opening modes

2077 · 5 marks

Why file is used in programming? Explain different file opening modes. [5]

Files are used in programming for the following reasons: 1. Permanent/Persistent Storage: Data stored in variables and arrays is lost when the program terminates. Files allow data to be stored permanently on secondary storage (disk). 2. Large Data Handling: Files allow programs to handle large am...

Open this answer on its own page →

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]

Feature fgets() fgetc() --------- Purpose Reads a string (line) from a file Reads a single character from a file Syntax fgets(str, n, fp) fgetc(fp) Return Type Returns char (pointer to string) Returns int (character as integer) Parameters Takes string buffer, size, and file pointer Takes only fil...

Open this answer on its own page →

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]

Parameters: Parameter Description ------------------------ ptr Pointer to the block of memory (data to be written) size Size in bytes of each element to be written count Number of elements to be written stream Pointer to the FILE object where data is written Return Value: - Returns the total numb...

Open this answer on its own page →