UNIT V FILEPROCESSING
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.
Definition:
A file is a collection of related data stored under a single name on a storage
device.
Key Points
● It has a name (example: [Link], [Link]).
● It has a type (text file, binary file).
● It stores data permanently (unlike variables, which store temporarily in
RAM).
● Files help in input/output operations in programs.
Types of Files
1. Text File (.txt) – stores human-readable characters.
2. Binary File (.bin) – stores data in binary format for fast processing.
Types of File Processing
File processing refers to the way data is accessed and read from or written to a
file. In C, there are two major types:
1. Sequential Access File Processing
Definition
Sequential access means data in the file is read or written in order, from the
beginning to the end.
Features
● Access happens one record after another.
● You cannot directly jump to any location.
● Suitable for reading full files.
Example Use Cases
● Reading marks list
● Log files
● Text documents
C Functions Used
● fopen()
● fprintf(), fscanf()
● fgetc(), fputc()
● fgets(), fputs()
● fclose()
Simple Diagram
Start → Read Record 1 → Record 2 → Record 3 → ... → End
2. Random Access File Processing (Direct Access)
Definition
Random access allows accessing any part of a file directly, without reading it
from the start.
Features
● Can move the file pointer to any position.
● Fast for large files.
● Best for record-based files.
C Functions Used
● fseek() → moves file pointer to any location
● ftell() → tells current file pointer position
● fwrite(), fread() (mostly for binary files)
Example Use Cases
● Accessing student record #50 directly
● Editing a specific part of a file
● Database-like applications
Simple Diagram
Jump directly to → Any location in the file
Sequential Access File – Example Program Finding Average of Numbers in
a File
#include <stdio.h>
int main() {
FILE *fp = fopen("[Link]", "r");
int n, c = 0;
float s = 0;
while (fscanf(fp, "%d", &n) != EOF) {
s += n;
c++;
}
printf("Average = %.2f", s / c);
fclose(fp);
}
Example [Link] file:
If [Link] contains:
10
20
30
40
50
Output:
Average = 30.00
Random Access (Transaction Processing)
#include <stdio.h>
struct acc{int id; float bal;};
int main(){
FILE *fp=fopen("[Link]","rb+");
struct acc a; int id; float amt;
scanf("%d%f",&id,&amt);
while(fread(&a,sizeof(a),1,fp))
if([Link]==id){
[Link]+=amt;
fseek(fp,-sizeof(a),1);
fwrite(&a,sizeof(a),1,fp);
printf("%.2f",[Link]); break;}
fclose(fp);
}
OR:
#include <stdio.h>
struct acc {
int id;
float bal;
};
int main() {
FILE *fp = fopen("[Link]", "rb+");
struct acc a;
int id;
float amt;
scanf("%d", &id); // enter account ID
while (fread(&a, sizeof(a), 1, fp)) {
if ([Link] == id) {
scanf("%f", &amt); // amount
[Link] += amt; // deposit
fseek(fp, -sizeof(a), 1);
fwrite(&a, sizeof(a), 1, fp);
printf("New Bal = %.2f", [Link]);
break;
}
}
fclose(fp);
}
How this program works
1. File used → [Link] (binary file)
Each record contains:
● id → account number
● bal → current balance
2. Random access operations
● fread() → read each record
● Compare the entered ID
● If found → update balance
● fseek() → move back one record
● fwrite() → rewrite the updated record
3. Supports transactions
● Deposit
● Withdraw
The output of your program depends on two things:
1. The contents of the file [Link]
2. The values you enter for account ID and amount
Example
Suppose [Link] contains three records (binary, but logically):
id bal
101 5000
102 3000
103 4500
Program Run
Enter account ID: 102
Enter amount: 500
Output:
New Bal = 3500.00
● The program finds account 102, adds 500 to the balance (3000 + 500 = 3500),
updates the file, and prints the new balance.
Command Line Arguments in C
Definition
Command line arguments allow the user to pass inputs to a program at the time of running
it from the command line or terminal, instead of using scanf() inside the program.
Syntax of main() for Command Line Arguments
int main(int argc, char *argv[])
or equivalently
int main(int argc, char **argv)
Parameters
Paramet
Meaning
er
Argument count – the number of arguments passed including the program
argc
name
argv Argument vector – an array of strings containing each argument
Example Program
Add two numbers using command line arguments
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if(argc != 3) { // Check if 2 numbers are given
printf("Usage: ./[Link] num1 num2\n");
return 1;
}
int a = atoi(argv[1]); // convert string to int
int b = atoi(argv[2]);
printf("Sum = %d\n", a + b);
return 0;
}
How to Run
gcc program.c -o add
./add 10 20
Output:
Sum = 30
Key Points
1. argv[0] → Name of the program (./add)
2. argv[1] → First argument (10)
3. argv[2] → Second argument (20)
4. argc → Total number of arguments (3 in this case)
5. Always convert string arguments to numbers using atoi() or atof() for numeric
operations.
Question Bank Answer:
[Link] a c program for command line arguments to add
two numbers.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if(argc != 3) { // check if 2 numbers are given
printf("Usage: ./[Link] num1 num2\n");
return 1;
}
int a = atoi(argv[1]); // first number
int b = atoi(argv[2]); // second number
printf("a = %d, b = %d\n", a, b);
printf("Sum = %d\n", a + b);
return 0;
}
Output:
a = 10, b = 20
Sum = 30
[Link] the function of fseek() and ftell() with an example
program.
Files in C can be accessed sequentially or randomly.
fseek() and ftell() are used for random access, i.e., to move the file pointer and
know its position.
1. fseek() Function
Definition
fseek() is used to move the file pointer to a specific location in a file.
Syntax
int fseek(FILE *fp, long offset, int whence);
Parameters
Parameter Description
fp Pointer to the file
offset Number of bytes to move
Starting position for offset:
- SEEK_SET → beginning of file
whence
- SEEK_CUR → current position
- SEEK_END → end of file
Return Value
● 0 → success
● -1 → error
2. ftell() Function
Definition
ftell() returns the current position of the file pointer in bytes from the
beginning of the file.
Syntax
long ftell(FILE *fp);
Return Value
● Current position in bytes
● -1L if an error occurs
Example Program
Task: Write numbers to a file and read the 3rd number using random access.
#include <stdio.h>
int main() {
FILE *fp;
int n;
// Write numbers 1 to 5 to file
fp = fopen("[Link]", "wb");
for(int i=1; i<=5; i++)
fwrite(&i, sizeof(int), 1, fp);
fclose(fp);
// Read 3rd number using fseek
fp = fopen("[Link]", "rb");
fseek(fp, 2 * sizeof(int), SEEK_SET); // move to 3rd number
fread(&n, sizeof(int), 1, fp);
printf("3rd number = %d\n", n);
// Get current position using ftell
printf("Current position in file = %ld bytes\n", ftell(fp));
fclose(fp);
return 0;
}
Output
3rd number = 3
Current position in file = 12 bytes
Explanation
1. fseek(fp, 2*sizeof(int), SEEK_SET) → skips first 2 integers (each 4
bytes) to reach the 3rd number.
2. ftell(fp) → returns 12, the number of bytes from the beginning of the file.
3. Useful in random access for reading/updating specific records.
[Link] a C program to read name and marks of “N” number of students
from user and store them in a file?
#include <stdio.h>
struct student {
char name[50];
int marks;
};
int main() {
FILE *fp = fopen("[Link]","w");
int n;
scanf("%d",&n);
struct student s;
for(int i=0;i<n;i++){
scanf("%s %d", [Link], &[Link]);
fprintf(fp,"%s %d\n", [Link], [Link]);
}
fclose(fp);
}
4.(i)Compute short notes on fscanf ().
(i)Compute short notes on fprintf ().
fscanf()
Definition:
fscanf() is a file input function used to read formatted data from a file, similar
to how scanf() reads from the keyboard.
Syntax:
int fscanf(FILE *fp, const char *format, ...);
Parameters:
Paramete
Description
r
fp Pointer to the file to read from
format Format specifier (like %d, %s, %f)
Addresses of variables to store the read
...
data
Return Value:
● Number of items successfully read
● EOF if end of file is reached
Example:
FILE *fp = fopen("[Link]", "r");
int x;
fscanf(fp, "%d", &x); // read an integer from file
fclose(fp);
2. fprintf()
Definition:
fprintf() is a file output function used to write formatted data to a file, similar
to printf() which writes to the screen.
Syntax:
int fprintf(FILE *fp, const char *format, ...);
Parameters:
Parameter Description
fp Pointer to the file to write to
format Format specifier (like %d, %s, %f)
... Variables or values to write
Return Value:
● Number of characters written to the file
Example:
FILE *fp = fopen("[Link]", "w");
int x = 100;
fprintf(fp, "Value = %d\n", x); // write integer to file
fclose(fp);
Key Points:
● fscanf() → Reads data from a file
● fprintf() → Writes data to a file
● Both require a file pointer (FILE *fp)
● Format specifiers %d, %f, %s work the same as in scanf()/printf().