Unit 5 QB Answers
Unit 5 QB Answers
The `fopen()` function in C is used to open a file and associate it with a stream, allowing the program to read
from or write to the file.
7. `b` - Binary mode (used with other modes like `rb`, `wb`)
The fgetc() function in C reads a single character from a file and returns it as an int. If the end of the file is
reached or an error occurs, it returns EOF.
The `fread()` function in C is used to read a block of data from a file into memory, while the `fwrite()` function
is used to write a block of data from memory to a file. Both functions allow reading and writing multiple bytes
at once.
- `fread()` syntax: `size_t fread(void *ptr, size_t size, size_t count, FILE *stream);`
size_t, you can write more efficient and portable C code, especially when dealing with memory management
and data structures.
- Reads `count` objects, each of size `size`, from the file into the buffer pointed to by `ptr`.
- `fwrite()` syntax: `size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);`
- Writes `count` objects, each of size `size`, from the buffer pointed to by `ptr` to the file.
The `fseek()` and `ftell()` functions in C are used for file position management:
fseek()
Parameters:
ftell()
Purpose: Returns the current position of the file pointer within a file.
Parameter:
Return value: The current position of the file pointer in bytes, relative to the beginning of the file.
In this example, fseek(fp, 10, SEEK_SET) moves the file pointer to the 10th byte from the beginning of the file.
Then, ftell(fp) returns the current position of the file pointer, which should be 11 (after reading one character).
Sequential Access and Random Access are two different methods of accessing data in files:
1. Sequential Access:
- Example: Reading a file line by line or writing data in the order it arrives.
- Limitations: You cannot directly access a specific part of the file without reading from the beginning to that
point.
2. Random Access:
- Data can be accessed at any point in the file without reading the entire file from the start.
- Example: Using functions like `fseek()` to move the file pointer to a specific position and access data.
- Advantages: Allows efficient retrieval and modification of data at any location in the file.
Command-line arguments offer a powerful and flexible way to interact with programs, providing several key
advantages:
Flexibility: You can run the program with different inputs each time, making it versatile.
Automation: You can create scripts that automatically run your program with different arguments, saving
time and effort.
Power User Control: Advanced users can customize the program's behavior with specific options and
settings.
8. How do you move the file pointer to the beginning of a file?
To move the file pointer to the beginning of a file in C, you can use the `fseek()` function with `SEEK_SET` as
the reference point:
fseek(file_pointer, 0, SEEK_SET);
This sets the file pointer to the start (offset `0`) of the file.
10. Develop a c program to copy the contents of one file to another file.
#include <stdio.h>
int main() {
int ch;
if (source_file == NULL) {
return 1;
if (destination_file == NULL) {
fclose(source_file);
return 1;
}
fputc(ch, destination_file);
fclose(source_file);
fclose(destination_file);
return 0;
Explanation:
Opening Files:
fopen opens the source and destination files in read and write mode, respectively.
This process continues until the end of the source file is reached (EOF).
Closing Files:
Remember:
Replace "[Link]" and "[Link]" with the actual file names you want to use.
This simpler version is suitable for copying text files. For binary files, using fread and fwrite as in the previous
example is more efficient.
PART-B
1. Explain the details about files and its types of file processing?(16 MARKS)
A file is a named collection of data stored on a storage device. It's like a digital container that holds information.
Files can store various types of data, such as text, images, audio, video, and executable programs.
Sequential Access:
A sequential file is a type of file structure used in computer systems to organize and store data in a sequential
order. In a sequential file, records are stored one after another, with each new record being appended to the end
of the file. This means that the records are stored in the order they are added, and accessing the data follows a
sequential pattern from the beginning to the end of the file.
Data is accessed in a sequential manner, starting from the beginning of the file.
Examples:
Random or
Direct
Access:
A random
access file is
a type of file
structure
that allows
direct access
to any record within the file, enabling efficient searching, updating, and retrieval of individual records. Unlike
sequential access files where data is organized and accessed sequentially, random access files provide the ability
to access records in any order based on their position or key.
Suitable for large files or when you need to access specific parts of the file.
Examples:
File Pointer: A pointer that indicates the current position within a file.
File Modes:
w: Open a file for writing (creates a new file or truncates an existing one).
a: Open a file for appending (adds data to the end of the file).
w+: Open a file for both reading and writing (creates a new file or truncates an existing one).
File Operations:
By understanding these concepts and file operations, you can effectively work with files in C programming to
store, retrieve, and manipulate data.
2. Demonstrate a c program for command line arguments to add two numbers. (16 MARKS)
C program to calculate the area of a rectangle, taking the length and width as command-line arguments:
#include <stdio.h>
#include <stdlib.h>
if (argc != 3) {
return 1;
return 0;
Explanation:
Command-line Arguments:
argc: This variable stores the number of arguments passed to the program, including the program name itself.
argv: This is an array of strings, where each string represents an argument. argv[0] is the program name, argv[1]
is the first argument, and so on.
Argument Validation:
The program checks if exactly two arguments are provided. If not, it prints a usage message and exits.
atoi(argv[1]) and atoi(argv[2]) convert the first and second arguments from strings to integers.
The area variable stores the product of the length and width.
Therefore, the argc should be 3 to ensure that the program receives the correct number of inputs.
3. Write a c program to find the average of numbers stored in sequential access file. (16 MARKS)
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("[Link]", "r");
if (fp == NULL) {
return 1;
sum += num;
count++;
fclose(fp);
if (count > 0) {
} else {
return 0;
Explanation:
Reading Numbers:
fscanf(fp, "%d", &num) reads an integer from the file and stores it in the num variable.
The (float) cast is used to ensure floating-point division for accurate results.
Note:
Ensure that the "[Link]" file contains only integer numbers, one per line.
For more complex file formats or error handling, you may need to use more advanced file I/O techniques.
Consider using error checking mechanisms to handle potential errors like file not found or invalid input.
This code provides a basic approach to calculate the average of numbers from a sequential access file. You can
adapt it to handle different file formats and error conditions as needed.
A random access file allows data to be read or written in any order. Unlike sequential access files, where data
must be accessed sequentially, random access files enable direct access to any part of the file, making them
useful when you need quick access to specific data.
Let's write a program to demonstrate random access by managing student records in a binary file. Each record
contains a student ID, name, and marks.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int id;
char name[30];
float marks;
} Student;
Student s;
scanf("%d", &[Link]);
scanf("%s", [Link]);
scanf("%f", &[Link]);
int id;
Student s;
scanf("%d", &id);
if ([Link] == id) {
} else {
Student s;
printf("\nAll Records:\n");
int main() {
FILE *file;
int choice;
if (!file) {
if (!file) {
return 1;
do {
printf("\nMenu:\n");
printf("4. Exit\n");
scanf("%d", &choice);
switch (choice) {
case 1:
addRecord(file);
break;
case 2:
readRecord(file);
break;
case 3:
displayAllRecords(file);
break;
case 4:
fclose(file);
printf("Exiting program.\n");
break;
default:
return 0;
Structure Definition:
Adding Records:
The addRecord() function calculates the position in the file using fseek() and writes a new record.
The readRecord() function calculates the position in the file using fseek() and reads a specific record using the
student ID.
The displayAllRecords() function uses fread() to iterate through all records from the start of the file.
File Handling:
The program opens a file in binary read/write mode (rb+) or creates it if it doesn't exist (wb+).
Output Example
1. Add Record
2. Read Record
4. Exit
Output:
Output:
Student ID: 1
Name: Alice
Marks: 89.50
Input:
Output:
All Records:
[Link] a c program for transaction processing using random access file.(16 MARKS)
Below is a program for transaction processing using a random access file. This program simulates a simple
banking system where users can:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int accountNumber;
char name[30];
float balance;
} Account;
Account acc;
scanf("%d", &[Link]);
scanf("%s", [Link]);
int accountNumber;
Account acc;
scanf("%d", &accountNumber);
if ([Link] == accountNumber) {
printf("\nAccount Details:\n");
} else {
int accountNumber;
float amount;
Account acc;
scanf("%d", &accountNumber);
if ([Link] == accountNumber) {
return;
} else {
Account acc;
printf("\nAll Accounts:\n");
if ([Link] != 0) {
int main() {
FILE *file;
int choice;
if (!file) {
if (!file) {
return 1;
}
do {
printf("\nMenu:\n");
printf("6. Exit\n");
scanf("%d", &choice);
switch (choice) {
case 1:
addAccount(file);
break;
case 2:
viewAccount(file);
break;
case 3:
break;
case 4:
break;
case 5:
displayAllAccounts(file);
break;
case 6:
fclose(file);
printf("Exiting program.\n");
break;
default:
printf("Invalid choice. Try again.\n");
return 0;
Structure Definition:
The Account structure holds the account number, name, and balance.
Add Account:
The addAccount() function writes an account record to a calculated position based on the account number.
View Account:
The viewAccount() function reads a specific account record using the account number.
The depositOrWithdraw() function modifies the balance based on whether it’s a deposit or withdrawal.
The displayAllAccounts() function iterates through the file and displays all accounts.
File Handling:
The file is opened in binary read/write mode. If the file doesn’t exist, it is created.
Example Execution
Input:
1. Add Account
Output:
Input:
2. View Account
Output:
Account Details:
Name: John
Balance: 5000.00
Input:
3. Deposit Money
Output:
Input:
Output:
All Accounts:
6. Elaborate the function of fseek() and ftell() with an example program.(16 MARKS)
1. fseek():
2. ftell():
Example Program
The following program demonstrates how to use fseek() and ftell() for navigating a text file:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *file;
char ch;
// Open a file in write mode to create the file and write some data
if (!file) {
return 1;
fputs(content, file);
fclose(file);
if (!file) {
return 1;
ch = fgetc(file);
fseek(file, 5, SEEK_CUR);
printf("After moving 5 bytes before the end, ftell() reports position: %ld\n", ftell(file));
ch = fgetc(file);
fclose(file);
return 0;
fseek(file, 10, SEEK_SET) moves the pointer to the 10th byte from the start.
fseek(file, 5, SEEK_CUR) moves the pointer 5 bytes ahead from the current position.
fseek(file, -5, SEEK_END) moves the pointer 5 bytes back from the end.
Output Example
Output:
Key Points
fseek():
ftell():
Usage:
Together, fseek() and ftell() are essential for handling random access files effectively.
[Link] the various file functions used in a file processing with an example program.(16 MARKS)
File processing in C involves various functions for reading, writing, and managing files. Here’s a breakdown of
commonly used file functions:
Random Access:
This program demonstrates creating, writing, reading, and processing a text file using various file functions.
#include <stdio.h>
#include <stdlib.h>
char buffer[100];
printf("%s", buffer);
int lines = 0;
char ch;
if (ch == '\n') {
lines++;
int main() {
FILE *file;
int choice;
do {
printf("\nMenu:\n");
printf("4. Exit\n");
scanf("%d", &choice);
switch (choice) {
case 1:
if (!file) {
return 1;
writeToFile(file);
fclose(file);
break;
case 2:
if (!file) {
return 1;
readFromFile(file);
fclose(file);
break;
case 3:
if (!file) {
countLinesInFile(file);
fclose(file);
break;
case 4:
printf("Exiting program.\n");
break;
default:
return 0;
File Reading:
Counting Lines:
rewind() resets the file pointer to the beginning of the file for reprocessing.
Output Example
Input:
1. Write to File
Output:
Output:
Name: Alice
Age: 25
Input:
Output:
File Handling:
File Writing:
File Reading:
File Position:
Error Handling:
This program showcases how to use different file functions to perform common operations.
8. Construct a C program to read name and marks of “N” number of students from user and store them
in a file?(16 MARKS)
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char name[50];
float marks;
} Student;
int main() {
FILE *file;
int n, i;
Student student;
if (file == NULL) {
return 1;
scanf("%d", &n);
printf("Name: ");
printf("Marks: ");
scanf("%f", &[Link]);
fclose(file);
return 0;
Explanation
Structure Definition:
The program uses a Student structure to store a student's name and marks.
File Handling:
The file [Link] is opened in write mode using fopen(). If the file does not exist, it will be created.
Reading Input:
The user inputs the number of students and provides details (name and marks) for each student.
The scanf() function reads input. The format specifier %[^\n] ensures that strings with spaces are read.
Writing to File:
The program writes student data into the file in a structured format using fprintf().
File Closure:
The file is closed using fclose() to save changes and release resources.
Sample Input/Output
Input:
Name: Alice
Marks: 85.5
Name: Bob
Marks: 90.0
Student 1:
Name: Alice
Marks: 85.50
Student 2:
Name: Bob
Marks: 90.00
Console Message:
Key Points
Dynamic Input: The program can handle any number of students by using a loop.
Formatted Output: The student data is written to the file in a readable format.
Error Handling: Ensures that the file is opened successfully before proceeding.
This program demonstrates how to work with files and structures in C efficiently.
9. (i)Compute short notes on fscanf (). (i)Compute short notes on fprintf ().(16 MARKS)
(i) fscanf()
Purpose:
Syntax:
Parameters:
Key Features:
Example:
#include <stdio.h>
int main() {
FILE *file;
char name[50];
int age;
if (file == NULL) {
return 1;
fclose(file);
return 0;
Explanation:
(ii) fprintf()
Purpose:
Syntax:
Parameters:
Key Features:
Example:
#include <stdio.h>
int main() {
FILE *file;
if (file == NULL) {
return 1;
fclose(file);
return 0;
Explanation:
Alice 25
Purpose Reads formatted input from file Writes formatted output to file
Both functions are essential for formatted file input and output operations in C.
10. Incorporate the methodology of sequential access file with an example program.(16 MARKS)
Sequential access files allow data to be processed in a linear order. The file is read or written from the beginning
to the end without skipping or jumping positions.
Key Operations:
Use fopen() to open the file in read (r), write (w), append (a), or update modes (r+, w+, etc.).
Use functions like fgets(), fgetc(), fprintf(), or fputs() for sequential operations.
This program reads student records (name and marks) from the user and writes them to a file. Then, it
sequentially reads and displays the stored data.
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char name[50];
float marks;
} Student;
int main() {
FILE *file;
int n, i;
Student student;
if (file == NULL) {
return 1;
scanf("%d", &n);
printf("Name: ");
printf("Marks: ");
scanf("%f", &[Link]);
fclose(file);
if (file == NULL) {
return 1;
}
printf("---------------------------------------\n");
fclose(file);
return 0;
Explanation:
File Writing:
For each student, it collects name and marks and writes them to the file using fprintf().
File Reading:
fscanf() reads the data sequentially (line by line) until the end of the file (EOF).
Sequential Access:
Sample Input/Output:
Input:
Name: Alice
Marks: 85.5
Name: Bob
Marks: 90.0
Alice 85.50
Bob 90.00
Output:
---------------------------------------
Key Points:
Sequential Access:
Data is processed in order, making it simple and efficient for linear operations.
fopen(), fprintf(), fscanf(), and fclose() are used for file operations.
EOF Detection:
fscanf() returns EOF when the end of the file is reached, ensuring the loop terminates.
Sequential access is ideal for applications like reading logs, processing text files, and maintaining ordered data.