I I
24ESCS101
PROBLEM SOLVING & PROGRAMMING IN C
UNIT No. 6 -FILE PROCESSING
Files – Types of File Processing: Sequential Access, Random Access – Sequential Access File -
Example Program: Finding Average of Numbers stored in Sequential Access File - Random
Access File - Example Program: Transaction Processing Using Random Access Files –
Command Line Arguments.
24ESCS101
PROBLEM SOLVING & PROGRAMMING IN C
UNIT 6 - FILE PROCESSING
Files – Types of File Processing: Sequential Access, Random Access – Sequential Access File -
Example Program: Finding Average of Numbers stored in Sequential Access File - Random
Access File - Example Program: Transaction Processing Using Random Access Files –
Command Line Arguments.
6.1 Files:
In C programming, files are used to store data permanently on a disk or other storage device. The
data stored in files remains available even after the program execution is complete, making files
essential for persistent data storage.
Why Use Files?
1. Persistent Storage: Data stored in files remains available even after the program ends,
unlike data in variables, which is lost once the program finishes execution.
2. Large Data Handling: Files can store large amounts of data that cannot be held in
memory all at once.
3. Data Sharing: Files allow easy sharing and exchange of data between programs and
across different sessions.
4. Data Backup: Files provide a way to save and back up data securely.
Basic Operations on Files
The C programming language provides several functions to work with files, which are part of the
stdio.h library. The main file operations are:
1. Creating a file or opening an existing file.
2. Reading from a file.
24ESCS101
PROBLEM SOLVING & PROGRAMMING IN C
3. Writing to a file.
4. Closing a file.
File Types in C
In C, files can be classified into two main types:
1. Text Files: Store data as plain text (readable characters). Each line ends with a newline
character (\n), and files end with an EOF (End of File) character. Example: .txt, .csv Data
is stored in a human-readable format.
2. Binary Files: Store data in binary form (0s and 1s). Example: .dat, .bin Data is stored in
a format that is not human-readable but is efficient for the computer to process.
File Modes in C Programming
When working with files in C, you need to specify the file mode when opening a file using the
fopen() function. The file mode determines the operations you can perform on the file, such as
reading, writing, or appending.
Syntax:
FILE *fopen(const char *filename, const char *mode);
❖ filename: The name of the file you want to open.
❖ mode: The mode in which you want to open the file.
Common File Modes
24ESCS101
PROBLEM SOLVING & PROGRAMMING IN C
Modes for Binary Files
The modes mentioned above can also be used with binary files by adding a "b" to the mode
string. Binary files are useful when you need to read/write data in a format that is not human-
readable, such as images or compiled data.
24ESCS101
PROBLEM SOLVING & PROGRAMMING IN C
File Pointers
In C, files are accessed through file pointers, which are variables of type FILE*. A file
pointer keeps track of the position in the file for reading or writing.
Syntax:
FILE *filePointer;
Error Handling with Files
It's important to handle errors while working with files to ensure smooth program execution.
The common issues include:
● File not found or cannot be opened.
● Reading or writing errors.
Example:
24ESCS101
PROBLEM SOLVING & PROGRAMMING IN C
FILE *filePointer = fopen("[Link]", "r");
if (filePointer == NULL)
perror("Error opening file");
return 1;
perror() provides a description of the error encountered.
6.2 Types of File Processing: Sequential Access, Random Access
When working with files in C, there are two main types of file processing methods based on how
data is accessed and manipulated:
1. Sequential Access
2. Random Access (Direct Access)
Each method has its own use cases, advantages, and limitations.
1. Sequential Access File Processing
Sequential Access refers to reading or writing data in a linear order, starting from the beginning
of the file and moving towards the end. This is the simplest and most common form of file access.
Characteristics of Sequential Access:
❖ Data is processed in the order it appears in the file.
24ESCS101
PROBLEM SOLVING & PROGRAMMING IN C
❖ Suitable for reading or writing large blocks of data without the need to access specific
locations.
❖ Typically used for text files like logs, CSV files, or structured data where processing
occurs line by line.
❖ Slower when specific data needs to be retrieved from the middle or end of a large file.
Example: Sequential Access
#include <stdio.h>
int main() {
FILE *filePointer;
int num, sum = 0, count = 0;
// Open the file for reading
filePointer = fopen("[Link]", "r");
if (filePointer == NULL) {
printf("Error: Could not open file.\n");
return 1;
// Read numbers from the file sequentially and calculate the sum
while (fscanf(filePointer, "%d", &num) != EOF) {
sum += num;
count++;
24ESCS101
PROBLEM SOLVING & PROGRAMMING IN C
// Calculate the average
if (count > 0) {
printf("Average: %.2f\n", (float)sum / count);
} else {
printf("No data found in the file.\n");
// Close the file
fclose(filePointer);
return 0;
Explanation:
❖ The program reads numbers from a file [Link] sequentially until it reaches the end
of the file (EOF).
❖ It calculates the sum and average of the numbers.
❖ This method processes each number in the order it appears in the file.
Advantages of Sequential Access:
❖ Simple and easy to implement.
❖ Efficient for processing entire files or large blocks of data in order.
24ESCS101
PROBLEM SOLVING & PROGRAMMING IN C
Disadvantages of Sequential Access:
❖ Inefficient when specific data needs to be accessed directly.
❖ Not suitable for cases where quick access to specific data points is required.
2. Random Access (Direct Access) File Processing
Random Access, also known as Direct Access, allows data to be read from or written to any
position in the file without reading through the file sequentially. This type of file processing is
useful for scenarios where quick access to specific parts of the file is needed.
Characteristics of Random Access:
❖ Data can be accessed at any position in the file using file pointers.
❖ Suitable for binary files, databases, or files where specific records need to be updated
frequently.
❖ Uses functions like fseek(), ftell(), and rewind() to manipulate the file pointer.
Key Functions for Random Access:
1. fseek(FILE *fp, long offset, int origin): Moves the file pointer to a specified position.
origin can be:
❖ SEEK_SET (beginning of the file),
❖ SEEK_CUR (current position),
❖ SEEK_END (end of the file).
offset specifies the number of bytes to move the pointer.
Example:
fseek(fp, 10, SEEK_SET); // Move to the 10th byte from the beginning
24ESCS101
PROBLEM SOLVING & PROGRAMMING IN C
2. ftell(FILE *fp): Returns the current position of the file pointer.
Example:
long pos = ftell(fp);
printf("Current position: %ld\n", pos);
3. rewind(FILE *fp): Resets the file pointer to the beginning of the file.
Example:
rewind(fp);
Example: Random Access
#include <stdio.h>
struct Student {
int id;
char name[20];
float marks;
};
int main() {
FILE *filePointer;
struct Student student;
int recordNumber;
// Open the file in read/write binary mode
24ESCS101
PROBLEM SOLVING & PROGRAMMING IN C
filePointer = fopen("[Link]", "rb+");
if (filePointer == NULL) {
printf("Error: Could not open file.\n");
return 1;
// Prompt user to enter the record number to update
printf("Enter record number to update (starting from 0): ");
scanf("%d", &recordNumber);
// Calculate the position of the record
long offset = recordNumber * sizeof(struct Student);
// Use fseek to move the file pointer to the specific record
fseek(filePointer, offset, SEEK_SET);
// Read the student record
fread(&student, sizeof(struct Student), 1, filePointer);
printf("Current Data - ID: %d, Name: %s, Marks: %.2f\n", [Link], [Link],
[Link]);
// Update the marks of the student
printf("Enter new marks: ");
scanf("%f", &[Link]);
24ESCS101
PROBLEM SOLVING & PROGRAMMING IN C
// Move the file pointer back to the correct position and write the updated record
fseek(filePointer, offset, SEEK_SET);
fwrite(&student, sizeof(struct Student), 1, filePointer);
// Close the file
fclose(filePointer);
printf("Record updated successfully.\n");
return 0;
Explanation:
❖ The program updates a specific student record in a binary file [Link].
❖ It uses fseek() to move the file pointer to the correct position based on the record number.
❖ The record is read, modified, and then written back at the same position.
Advantages of Random Access:
❖ Fast access to specific data points without reading the entire file.
❖ Efficient for modifying specific parts of a large file.
❖ Suitable for applications like databases, where frequent updates to specific records are
needed.
Disadvantages of Random Access:
❖ More complex to implement compared to sequential access.
24ESCS101
PROBLEM SOLVING & PROGRAMMING IN C
❖ Requires knowledge of file structure (e.g., record size in binary files).
❖ Less efficient for reading large portions of data sequentially.
Summary of Sequential vs Random Access
6.3 Sequential Access File - Example Program: Finding Average of Numbers
stored in Sequential Access File
In this example, we will create a sequential access text file ([Link]) containing a list of
numbers. The program will then read these numbers sequentially and compute their average.
Steps Involved:
1. Create a file named [Link] with a list of integers (one number per line).
2. Open the file in read mode using "r".
3. Read the numbers from the file sequentially using fscanf().
4. Calculate the sum and count the number of entries.
5. Compute the average and display it.
[Link] (Sample File Content)
24ESCS101
PROBLEM SOLVING & PROGRAMMING IN C
10
20
30
40
50
C Program: Finding Average of Numbers in a Sequential Access File
#include <stdio.h>
int main() {
FILE *filePointer;
int number;
int sum = 0, count = 0;
float average;
// Open the file "[Link]" in read mode
filePointer = fopen("[Link]", "r");
if (filePointer == NULL) {
printf("Error: Could not open file.\n");
return 1; // Exit if file cannot be opened
24ESCS101
PROBLEM SOLVING & PROGRAMMING IN C
// Read numbers sequentially from the file until end of file (EOF)
while (fscanf(filePointer, "%d", &number) != EOF) {
sum += number; // Add each number to the sum
count++; // Increment the count of numbers
// Check if there were any numbers read from the file
if (count > 0) {
// Calculate the average
average = (float)sum / count;
printf("Sum of numbers: %d\n", sum);
printf("Total numbers: %d\n", count);
printf("Average of numbers: %.2f\n", average);
} else {
printf("No numbers found in the file.\n");
// Close the file
24ESCS101
PROBLEM SOLVING & PROGRAMMING IN C
fclose(filePointer);
return 0;
Explanation:
File Opening (fopen):
❖ The file [Link] is opened in read mode ("r").
❖ If the file does not exist or cannot be opened, the program prints an error message
and exits.
Reading the File (fscanf):
❖ The program reads each integer from the file sequentially using fscanf().
❖ fscanf() returns EOF (End of File) when it reaches the end of the file, causing the
loop to stop.
Calculating Sum and Average:
❖ The sum of the numbers is accumulated in the variable sum.
❖ The count of numbers is tracked using the count variable.
❖ The average is calculated as sum / count.
Output:
❖ The sum, count, and average of the numbers are printed.
File Closing (fclose):
❖ The file is closed after processing to free the resources.
24ESCS101
PROBLEM SOLVING & PROGRAMMING IN C
Output:
Sum of numbers: 150
Total numbers: 5
Average of numbers: 30.00
Explanation of Output:
● The program reads 5 numbers (10, 20, 30, 40, 50).
● It calculates their sum as 150 and their average as 30.00.
6.4 Random Access File - Example Program: Transaction Processing Using
Random Access Files
Random Access allows reading or writing data at any specific position in a file without
processing it sequentially. This is useful for applications like databases, where records are
accessed, updated, or deleted frequently.
Problem Statement:
We will create a random access file for a simple transaction processing system. The system will:
1. Store information about multiple accounts (ID, name, and balance).
2. Allow updating the account balance based on transactions.
3. Implement random access to update specific account information without reading the
entire file.
Structure of Data:
24ESCS101
PROBLEM SOLVING & PROGRAMMING IN C
We will use a binary file ([Link]) to store records of a structure Account. Each record will
include:
❖ Account ID (integer)
❖ Account holder's name (string)
❖ Account balance (float)
C Program: Transaction Processing Using Random Access Files
Explanation:
Structure Definition (Account):
❖ Each record in the file contains an Account structure with fields for ID, name, and
balance.
File Opening (fopen):
❖ The binary file [Link] is opened in read/write mode ("rb+").
❖ If the file does not exist, it is created ("wb+").
Writing Sample Data:
❖ Sample account data is written to the file for demonstration purposes.
Random Access with fseek():
❖ fseek() is used to move the file pointer to a specific record for updating the
balance.
24ESCS101
PROBLEM SOLVING & PROGRAMMING IN C
❖ fseek(filePointer, -sizeof(struct Account), SEEK_CUR) moves the file pointer
back by the size of an Account record, allowing us to overwrite the record at its
current position.
Updating Account Balance:
❖ The balance is updated based on deposit or withdrawal transactions.
❖ The program reads the account, modifies the balance, and writes the updated
record back to the file.
Displaying Records:
❖ The displayAccounts() function reads and displays all the account records.
Sample Output:
Initializing accounts data...
List of Accounts:
ID Name Balance
1 Alice 1000.00
2 Bob 1500.50
3 Charlie 2000.75
4 Diana 2500.00
Transaction Menu:
1. Deposit
24ESCS101
PROBLEM SOLVING & PROGRAMMING IN C
2. Withdraw
3. Display All Accounts
4. Exit
Enter your choice: 1
Enter Account ID for deposit: 2
Enter deposit amount: 500
Account ID 2 updated successfully. New balance: 2000.50
Transaction Menu:
1. Deposit
2. Withdraw
3. Display All Accounts
4. Exit
Enter your choice: 3
List of Accounts:
ID Name Balance
1 Alice 1000.00
2 Bob 2000.50
24ESCS101
PROBLEM SOLVING & PROGRAMMING IN C
3 Charlie 2000.75
4 Diana 2500.00
6.5 Command Line Arguments
Command Line Arguments are inputs given to a C program at the time of execution through
the terminal or command prompt. These arguments are passed to the main() function when the
program starts.
Syntax of main() with Command Line Arguments:
int main(int argc, char *argv[])
argc: (Argument Count)
❖ An integer representing the number of command-line arguments passed to the program,
including the program's name.
❖ It is always at least 1 because the first argument (argv[0]) is the name of the program.
argv: (Argument Vector)
❖ An array of character pointers (strings) that contains the actual arguments passed to the
program.
❖ argv[0] holds the program name, argv[1] holds the first argument, argv[2] holds the
second argument, and so on.
24ESCS101
PROBLEM SOLVING & PROGRAMMING IN C
Example : Simple Command Line Argument Program
This program displays the command-line arguments passed to it.
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("Number of arguments (argc): %d\n", argc);
// Displaying the arguments
for (int i = 0; i < argc; i++) {
printf("Argument %d (argv[%d]): %s\n", i, i, argv[i]);
return 0;
How to Run:
$ gcc program.c -o program
$ ./program Hello World 123
Output:
Number of arguments (argc): 4
Argument 0 (argv[0]): ./program
24ESCS101
PROBLEM SOLVING & PROGRAMMING IN C
Argument 1 (argv[1]): Hello
Argument 2 (argv[2]): World
Argument 3 (argv[3]): 123
Explanation:
❖ argc is 4 because the program name and three arguments (Hello, World, 123) are passed.
❖ argv is an array of strings, where each element points to a corresponding argument.
Advantages of Using Command Line Arguments:
1. Flexibility: Users can pass different arguments without modifying the source code.
2. Automation: Enables batch processing or script automation by passing various
parameters to the program.
3. Versatility: Useful for file handling, mathematical computations, and dynamic input
handling.