0% found this document useful (0 votes)
19 views33 pages

Unit 5 QB Answers

This document provides a comprehensive overview of file handling in C, including functions like fopen(), fgetc(), fread(), fwrite(), fseek(), and ftell(). It distinguishes between sequential and random access file methods, explains command-line arguments, and includes example programs for copying files, calculating areas, and managing student records. Additionally, it outlines the types of file processing and key concepts related to file operations.

Uploaded by

surendharsharmi6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views33 pages

Unit 5 QB Answers

This document provides a comprehensive overview of file handling in C, including functions like fopen(), fgetc(), fread(), fwrite(), fseek(), and ftell(). It distinguishes between sequential and random access file methods, explains command-line arguments, and includes example programs for copying files, calculating areas, and managing student records. Additionally, it outlines the types of file processing and key concepts related to file operations.

Uploaded by

surendharsharmi6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT -5 ( 2 & 16 MARKS QUESTION BANK ANSWERS)

[Link] is the purpose of the fopen() function in C?

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.

2. Mention the modes of opening a file in C.

The modes of opening a file in C are:

1. `r` - Read mode

2. `w` - Write mode

3. `a` - Append mode

4. `r+` - Read and write mode

5. `w+` - Write and read mode

6. `a+` - Append and read mode

7. `b` - Binary mode (used with other modes like `rb`, `wb`)

3. What does the fgetc() function do in C?

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.

4. What is the purpose of the fread() and fwrite() function in C?

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 is a special unsigned integer type defined in the C standard library

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.

[Link] the functionality of fseek() and ftell()

The `fseek()` and `ftell()` functions in C are used for file position management:

fseek()

Purpose: Repositions the file pointer to a specific location within a file.

Syntax: int fseek(FILE *stream, long offset, int origin);

Parameters:

stream: A pointer to the file stream.

offset: The number of bytes to offset from the specified origin.


origin: The reference point for the offset:

SEEK_SET: Beginning of the file

SEEK_CUR: Current position of the file pointer

SEEK_END: End of the file

ftell()

Purpose: Returns the current position of the file pointer within a file.

Syntax: long ftell(FILE *stream);

Parameter:

stream: A pointer to the file stream.

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

6. Compare the sequential access and random access methods in files.

Sequential Access and Random Access are two different methods of accessing data in files:

1. Sequential Access:

- Data is read or written in a sequential order, one after another.

- Commonly used for text files or streaming data.

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

- Commonly used for binary files and databases.

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

7. Conclude the benefits of command line arguments.

Command-line arguments offer a powerful and flexible way to interact with programs, providing several key
advantages:

Command line arguments provide several benefits:

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.

9. Distinguish between binary file and text file.

10. Develop a c program to copy the contents of one file to another file.

#include <stdio.h>

int main() {

FILE *source_file, *destination_file;

int ch;

source_file = fopen("[Link]", "r");

if (source_file == NULL) {

perror("Error opening source file");

return 1;

destination_file = fopen("[Link]", "w");

if (destination_file == NULL) {

perror("Error opening destination file");

fclose(source_file);

return 1;
}

while ((ch = fgetc(source_file)) != EOF) {

fputc(ch, destination_file);

fclose(source_file);

fclose(destination_file);

printf("File copied successfully.\n");

return 0;

Explanation:

Opening Files:

fopen opens the source and destination files in read and write mode, respectively.

Copying Character by Character:

fgetc reads a character from the source file.

fputc writes the character to the destination file.

This process continues until the end of the source file is reached (EOF).

Closing Files:

fclose closes both 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)

Files: A Digital Storage Unit

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.

Types of File Processing:

There are two primary types of file processing:

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.

Each data item is read or written one after the other.


Suitable for small files or when you need to process the entire file.

Examples:

Reading a text file line by line.

Writing data to a log file.

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.

Data can be accessed directly at any location within the file.

This is achieved by using a file pointer to specify the desired position.

Suitable for large files or when you need to access specific parts of the file.

Examples:

Reading a specific record from a database file.

Updating a particular section of a configuration file.


Key Concepts in File Processing:

File Pointer: A pointer that indicates the current position within a file.

File Modes:

r: Open a file for reading.

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

r+: Open a file for both reading and writing.

w+: Open a file for both reading and writing (creates a new file or truncates an existing one).

a+: Open a file for both reading and appending.

File Operations:

fopen: Opens a file.

fclose: Closes a file.

fgetc: Reads a character from a file.

fputc: Writes a character to a file.

fgets: Reads a line from a file.

fputs: Writes a line to a file.

fread: Reads a block of data from a file.

fwrite: Writes a block of data to a file.

fseek: Moves the file pointer to a specific position.


ftell: Gets the current position of the file pointer.

feof: Checks if the end of a file has been reached.

ferror: Checks for errors in 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>

int main(int argc, char *argv[]) {

if (argc != 3) {

printf("Usage: %s <length> <width>\n", argv[0]);

return 1;

int length = atoi(argv[1]);

int width = atoi(argv[2]);

int area = length * width;

printf("The area of the rectangle is: %d\n", area);

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.

Converting Arguments to Integers:

atoi(argv[1]) and atoi(argv[2]) convert the first and second arguments from strings to integers.

Calculating the Area:

The area variable stores the product of the length and width.

Printing the Result:

The printf statement displays the calculated area.


Why 3 Arguments?

In this specific case, the program expects three arguments:

argv[0]: The name of the program itself.

argv[1]: The first number to be added.

argv[2]: The second number to be added.

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;

int num, count = 0, sum = 0;

fp = fopen("[Link]", "r");

if (fp == NULL) {

perror("Error opening file");

return 1;

while (fscanf(fp, "%d", &num) == 1) {

sum += num;

count++;

fclose(fp);

if (count > 0) {

float average = (float)sum / count;

printf("Average of numbers: %.2f\n", average);

} else {

printf("No numbers found in the file.\n");

return 0;

Explanation:

Opening the File:

fopen("[Link]", "r") opens the file "[Link]" in read mode.

Reading Numbers:
fscanf(fp, "%d", &num) reads an integer from the file and stores it in the num variable.

The loop continues until no more integers can be read.

Calculating Sum and Count:

The sum variable accumulates the sum of all read numbers.

The count variable keeps track of the number of numbers read.

Calculating the Average:

The average is calculated by dividing the sum by the count.

The (float) cast is used to ensure floating-point division for accurate results.

Printing the Result:

The calculated average is printed to the console.

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.

[Link] about random access file with an example program.(16 MARKS)

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.

In C, random access is achieved using functions like:

fseek() - Moves the file pointer to a specific position.

ftell() - Returns the current file pointer position.

rewind() - Moves the file pointer to the beginning of the file.

Example: Managing Student Records

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;

void addRecord(FILE *file) {

Student s;

printf("Enter Student ID: ");

scanf("%d", &[Link]);

printf("Enter Name: ");

scanf("%s", [Link]);

printf("Enter Marks: ");

scanf("%f", &[Link]);

fseek(file, ([Link] - 1) * sizeof(Student), SEEK_SET); // Move to the correct position

fwrite(&s, sizeof(Student), 1, file);

printf("Record added successfully.\n");

void readRecord(FILE *file) {

int id;

Student s;

printf("Enter Student ID to retrieve: ");

scanf("%d", &id);

fseek(file, (id - 1) * sizeof(Student), SEEK_SET); // Move to the correct position

fread(&s, sizeof(Student), 1, file);

if ([Link] == id) {

printf("Student ID: %d\n", [Link]);

printf("Name: %s\n", [Link]);

printf("Marks: %.2f\n", [Link]);

} else {

printf("No record found for ID %d.\n", id);

void displayAllRecords(FILE *file) {

Student s;

rewind(file); // Move to the start of the file

printf("\nAll Records:\n");

while (fread(&s, sizeof(Student), 1, file)) {


printf("Student ID: %d, Name: %s, Marks: %.2f\n", [Link], [Link], [Link]);

int main() {

FILE *file;

int choice;

file = fopen("[Link]", "rb+");

if (!file) {

file = fopen("[Link]", "wb+"); // Create the file if it doesn't exist

if (!file) {

printf("Error opening file.\n");

return 1;

do {

printf("\nMenu:\n");

printf("1. Add Record\n");

printf("2. Read Record\n");

printf("3. Display All Records\n");

printf("4. Exit\n");

printf("Enter your choice: ");

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:

printf("Invalid choice. Try again.\n");

} while (choice != 4);

return 0;

Explanation of the Program

Structure Definition:

A Student structure is defined to store id, name, and marks.

Adding Records:

The addRecord() function calculates the position in the file using fseek() and writes a new record.

Reading Specific Records:

The readRecord() function calculates the position in the file using fseek() and reads a specific record using the
student ID.

Displaying All Records:

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

3. Display All Records

4. Exit

Enter your choice: 1

Enter Student ID: 1

Enter Name: Alice

Enter Marks: 89.5

Output:

Record added successfully.


Input:

Enter your choice: 2

Enter Student ID to retrieve: 1

Output:

Student ID: 1

Name: Alice

Marks: 89.50

Input:

Enter your choice: 3

Output:

All Records:

Student ID: 1, Name: Alice, Marks: 89.50

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

Add account records.

View a specific account.

Deposit or withdraw money.

Display all accounts.

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

typedef struct {

int accountNumber;

char name[30];

float balance;

} Account;

void addAccount(FILE *file) {

Account acc;

printf("Enter Account Number: ");

scanf("%d", &[Link]);

printf("Enter Account Holder Name: ");

scanf("%s", [Link]);

printf("Enter Initial Balance: ");


scanf("%f", &[Link]);

fseek(file, ([Link] - 1) * sizeof(Account), SEEK_SET); // Move to correct position

fwrite(&acc, sizeof(Account), 1, file);

printf("Account added successfully.\n");

void viewAccount(FILE *file) {

int accountNumber;

Account acc;

printf("Enter Account Number to view: ");

scanf("%d", &accountNumber);

fseek(file, (accountNumber - 1) * sizeof(Account), SEEK_SET); // Move to correct position

fread(&acc, sizeof(Account), 1, file);

if ([Link] == accountNumber) {

printf("\nAccount Details:\n");

printf("Account Number: %d\n", [Link]);

printf("Name: %s\n", [Link]);

printf("Balance: %.2f\n", [Link]);

} else {

printf("No account found with number %d.\n", accountNumber);

void depositOrWithdraw(FILE *file, int isDeposit) {

int accountNumber;

float amount;

Account acc;

printf("Enter Account Number: ");

scanf("%d", &accountNumber);

fseek(file, (accountNumber - 1) * sizeof(Account), SEEK_SET);

fread(&acc, sizeof(Account), 1, file);

if ([Link] == accountNumber) {

printf("Current Balance: %.2f\n", [Link]);

printf("Enter Amount to %s: ", isDeposit ? "Deposit" : "Withdraw");


scanf("%f", &amount);

if (!isDeposit && [Link] < amount) {

printf("Insufficient funds for withdrawal.\n");

return;

[Link] += isDeposit ? amount : -amount;

fseek(file, (accountNumber - 1) * sizeof(Account), SEEK_SET);

fwrite(&acc, sizeof(Account), 1, file);

printf("%s successful. New Balance: %.2f\n", isDeposit ? "Deposit" : "Withdrawal", [Link]);

} else {

printf("No account found with number %d.\n", accountNumber);

void displayAllAccounts(FILE *file) {

Account acc;

rewind(file); // Move to the start of the file

printf("\nAll Accounts:\n");

while (fread(&acc, sizeof(Account), 1, file)) {

if ([Link] != 0) {

printf("Account Number: %d, Name: %s, Balance: %.2f\n", [Link], [Link],


[Link]);

int main() {

FILE *file;

int choice;

file = fopen("[Link]", "rb+");

if (!file) {

file = fopen("[Link]", "wb+"); // Create the file if it doesn't exist

if (!file) {

printf("Error opening file.\n");

return 1;
}

do {

printf("\nMenu:\n");

printf("1. Add Account\n");

printf("2. View Account\n");

printf("3. Deposit Money\n");

printf("4. Withdraw Money\n");

printf("5. Display All Accounts\n");

printf("6. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

addAccount(file);

break;

case 2:

viewAccount(file);

break;

case 3:

depositOrWithdraw(file, 1); // Deposit

break;

case 4:

depositOrWithdraw(file, 0); // Withdraw

break;

case 5:

displayAllAccounts(file);

break;

case 6:

fclose(file);

printf("Exiting program.\n");

break;

default:
printf("Invalid choice. Try again.\n");

} while (choice != 6);

return 0;

Explanation of the Program

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.

Deposit and Withdraw:

The depositOrWithdraw() function modifies the balance based on whether it’s a deposit or withdrawal.

It checks for sufficient funds in case of a withdrawal.

Display All Accounts:

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

Enter Account Number: 101

Enter Account Holder Name: John

Enter Initial Balance: 5000

Output:

Account added successfully.

Input:

2. View Account

Enter Account Number to view: 101

Output:
Account Details:

Account Number: 101

Name: John

Balance: 5000.00

Input:

3. Deposit Money

Enter Account Number: 101

Enter Amount to Deposit: 1000

Output:

Deposit successful. New Balance: 6000.00

Input:

5. Display All Accounts

Output:

All Accounts:

Account Number: 101, Name: John, Balance: 6000.00

6. Elaborate the function of fseek() and ftell() with an example program.(16 MARKS)

1. fseek():

Purpose: Moves the file pointer to a specified position in the file.

Syntax: int fseek(FILE *stream, long offset, int whence);

stream: File pointer.

offset: Number of bytes to move.

whence: Reference position.

SEEK_SET: Beginning of the file.

SEEK_CUR: Current position of the file pointer.

SEEK_END: End of the file.

2. ftell():

Purpose: Returns the current position of the file pointer.

Syntax: long ftell(FILE *stream);

Returns the offset in bytes from the beginning of the file.

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 content[] = "This is a demonstration of fseek() and ftell().";

char ch;

// Open a file in write mode to create the file and write some data

file = fopen("[Link]", "w");

if (!file) {

printf("Error opening file.\n");

return 1;

// Write data to the file

fputs(content, file);

fclose(file);

// Open the file in read mode

file = fopen("[Link]", "r");

if (!file) {

printf("Error opening file.\n");

return 1;

printf("Reading file content using fseek() and ftell():\n");

// Move to the 10th byte using fseek()

fseek(file, 10, SEEK_SET);

printf("After fseek() to 10th byte, ftell() reports position: %ld\n", ftell(file));

// Read and display one character

ch = fgetc(file);

printf("Character at 10th byte: %c\n", ch);

// Move 5 bytes forward from the current position

fseek(file, 5, SEEK_CUR);

printf("After moving 5 bytes forward, ftell() reports position: %ld\n", ftell(file));

// Read and display one character


ch = fgetc(file);

printf("Character at new position: %c\n", ch);

// Move to 5 bytes before the end of the file

fseek(file, -5, SEEK_END);

printf("After moving 5 bytes before the end, ftell() reports position: %ld\n", ftell(file));

// Read and display one character

ch = fgetc(file);

printf("Character 5 bytes before the end: %c\n", ch);

fclose(file);

return 0;

Explanation of the Program

Write Content to a File:

A text file ([Link]) is created with predefined content.

fseek() and ftell() Usage:

Seek to the 10th Byte:

fseek(file, 10, SEEK_SET) moves the pointer to the 10th byte from the start.

ftell(file) returns the current position (10).

Move Forward by 5 Bytes:

fseek(file, 5, SEEK_CUR) moves the pointer 5 bytes ahead from the current position.

ftell(file) returns the updated position.

Seek to 5 Bytes Before the End:

fseek(file, -5, SEEK_END) moves the pointer 5 bytes back from the end.

ftell(file) returns the position.

Read Characters at Positions:

fgetc(file) reads a character at the current pointer position.

Output Example

Assume the content of [Link] is:


This is a demonstration of fseek() and ftell().

Output:

Reading file content using fseek() and ftell():

After fseek() to 10th byte, ftell() reports position: 10


Character at 10th byte: a

After moving 5 bytes forward, ftell() reports position: 15

Character at new position: m

After moving 5 bytes before the end, ftell() reports position: 38

Character 5 bytes before the end: l

Key Points

fseek():

Enables random access to any position in a file.

Useful for skipping parts of a file or reading/writing at specific locations.

ftell():

Tracks the current position of the file pointer.

Useful for debugging or determining file pointer locations dynamically.

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:

File Opening and Closing:

fopen(): Opens a file.

fclose(): Closes a file.

Reading and Writing:

fgetc(): Reads a single character.

fgets(): Reads a string.

fscanf(): Reads formatted input.

fputc(): Writes a single character.

fputs(): Writes a string.

fprintf(): Writes formatted output.

Random Access:

fseek(): Moves the file pointer.

ftell(): Returns the current file pointer position.

rewind(): Moves the file pointer to the beginning.


End-of-File Checking:

feof(): Checks if the end of the file has been reached.

Example Program: File Processing with Various Functions

This program demonstrates creating, writing, reading, and processing a text file using various file functions.

#include <stdio.h>

#include <stdlib.h>

void writeToFile(FILE *file) {

fprintf(file, "Name: Alice\n");

fprintf(file, "Age: 25\n");

fprintf(file, "Department: Computer Science\n");

printf("Data written to file successfully.\n");

void readFromFile(FILE *file) {

char buffer[100];

printf("\nReading data from file:\n");

while (fgets(buffer, sizeof(buffer), file)) {

printf("%s", buffer);

void countLinesInFile(FILE *file) {

int lines = 0;

char ch;

rewind(file); // Move to the beginning of the file

while ((ch = fgetc(file)) != EOF) {

if (ch == '\n') {

lines++;

printf("\nTotal number of lines in file: %d\n", lines);

int main() {
FILE *file;

int choice;

do {

printf("\nMenu:\n");

printf("1. Write to File\n");

printf("2. Read from File\n");

printf("3. Count Lines in File\n");

printf("4. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

file = fopen("[Link]", "w");

if (!file) {

printf("Error opening file.\n");

return 1;

writeToFile(file);

fclose(file);

break;

case 2:

file = fopen("[Link]", "r");

if (!file) {

printf("Error opening file.\n");

return 1;

readFromFile(file);

fclose(file);

break;

case 3:

file = fopen("[Link]", "r");

if (!file) {

printf("Error opening file.\n");


return 1;

countLinesInFile(file);

fclose(file);

break;

case 4:

printf("Exiting program.\n");

break;

default:

printf("Invalid choice. Try again.\n");

} while (choice != 4);

return 0;

Explanation of the Program

File Creation and Writing:

fopen("[Link]", "w") creates or opens a file for writing.

fprintf() writes formatted data to the file.

File Reading:

fopen("[Link]", "r") opens the file for reading.

fgets() reads lines from the file.

Counting Lines:

The countLinesInFile() function uses fgetc() to count newline characters.

Rewinding the File:

rewind() resets the file pointer to the beginning of the file for reprocessing.

Output Example

Input:

1. Write to File

Output:

Data written to file successfully.


Input:

2. Read from File

Output:

Reading data from file:

Name: Alice

Age: 25

Department: Computer Science

Input:

3. Count Lines in File

Output:

Total number of lines in file: 3

Key Functions Used

File Handling:

fopen() and fclose() for opening and closing files.

File Writing:

fprintf() for formatted output.

File Reading:

fgets() for reading lines.

fgetc() for reading individual characters.

File Position:

rewind() to reset the pointer.

Error Handling:

Checked if file == NULL to ensure the file was opened successfully.

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;

// Open the file for writing

file = fopen("[Link]", "w");

if (file == NULL) {

printf("Error opening file.\n");

return 1;

// Read the number of students

printf("Enter the number of students: ");

scanf("%d", &n);

// Get student details and write to file

for (i = 0; i < n; i++) {

printf("\nEnter details for student %d:\n", i + 1);

printf("Name: ");

scanf(" %[^\n]", [Link]); // Read string with spaces

printf("Marks: ");

scanf("%f", &[Link]);

fprintf(file, "Student %d:\n", i + 1);

fprintf(file, "Name: %s\n", [Link]);

fprintf(file, "Marks: %.2f\n\n", [Link]);

printf("\nStudent data has been successfully written to '[Link]'.\n");

// Close the file

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:

Enter the number of students: 2

Enter details for student 1:

Name: Alice

Marks: 85.5

Enter details for student 2:

Name: Bob

Marks: 90.0

Output (File Content: [Link]):

Student 1:

Name: Alice

Marks: 85.50

Student 2:

Name: Bob

Marks: 90.00

Console Message:

Student data has been successfully written to '[Link]'.

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:

fscanf() is used to read formatted input from a file.

Syntax:

int fscanf(FILE *stream, const char *format, ...);

Parameters:

stream: Pointer to the file (e.g., obtained from fopen()).

format: Format string specifying the type of data to read.

...: Additional arguments to store the read values (pointers).

Key Features:

Similar to scanf(), but works with files.

Reads data from the specified file and stores it in variables.

Common Use Cases:

Reading structured data like names, numbers, or records from a file.

Example:

#include <stdio.h>

int main() {

FILE *file;

char name[50];

int age;

// Open file for reading

file = fopen("[Link]", "r");

if (file == NULL) {

printf("Error opening file.\n");

return 1;

// Read data from file

fscanf(file, "%s %d", name, &age);

printf("Name: %s, Age: %d\n", name, age);

fclose(file);

return 0;

Explanation:

If the file [Link] contains:


Alice 25

The program will output:

Name: Alice, Age: 25

(ii) fprintf()

Purpose:

fprintf() is used to write formatted output to a file.

Syntax:

int fprintf(FILE *stream, const char *format, ...);

Parameters:

stream: Pointer to the file (e.g., obtained from fopen()).

format: Format string specifying how to format the output.

...: Additional arguments to write to the file.

Key Features:

Similar to printf(), but works with files.

Writes data in a specified format to the file.

Common Use Cases:

Storing structured data like names, numbers, or records in a file.

Example:

#include <stdio.h>

int main() {

FILE *file;

char name[50] = "Alice";

int age = 25;

// Open file for writing

file = fopen("[Link]", "w");

if (file == NULL) {

printf("Error opening file.\n");

return 1;

// Write data to file

fprintf(file, "%s %d\n", name, age);


printf("Data written to file.\n");

fclose(file);

return 0;

Explanation:

The file [Link] will contain:

Alice 25

Comparison Between fscanf() and fprintf()

Feature fscanf() fprintf()

Purpose Reads formatted input from file Writes formatted output to file

Input/Output Input operation Output operation

Syntax Similar to scanf() Similar to printf()

Usage Read structured data Store structured data

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:

Opening the File:

Use fopen() to open the file in read (r), write (w), append (a), or update modes (r+, w+, etc.).

Reading or Writing Sequentially:

Use functions like fgets(), fgetc(), fprintf(), or fputs() for sequential operations.

Closing the File:

Use fclose() to close the file after operations.

Example Program: Sequential Access File

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;

// Open the file for writing

file = fopen("students_sequential.txt", "w");

if (file == NULL) {

printf("Error opening file for writing.\n");

return 1;

// Read the number of students

printf("Enter the number of students: ");

scanf("%d", &n);

// Sequentially write student data to the file

for (i = 0; i < n; i++) {

printf("\nEnter details for student %d:\n", i + 1);

printf("Name: ");

scanf(" %[^\n]", [Link]); // Read string with spaces

printf("Marks: ");

scanf("%f", &[Link]);

fprintf(file, "%s %.2f\n", [Link], [Link]);

fclose(file);

printf("\nStudent data has been written to 'students_sequential.txt'.\n");

// Open the file for reading

file = fopen("students_sequential.txt", "r");

if (file == NULL) {

printf("Error opening file for reading.\n");

return 1;
}

printf("\nReading data from the file sequentially:\n");

printf("---------------------------------------\n");

// Sequentially read and display student data

while (fscanf(file, "%s %f", [Link], &[Link]) != EOF) {

printf("Name: %s, Marks: %.2f\n", [Link], [Link]);

fclose(file);

return 0;

Explanation:

File Writing:

The program prompts the user for the number of students.

For each student, it collects name and marks and writes them to the file using fprintf().

File Reading:

The file is reopened in read mode (r).

fscanf() reads the data sequentially (line by line) until the end of the file (EOF).

Sequential Access:

Writing and reading occur sequentially without skipping any data.

Each operation starts where the last one ended.

Sample Input/Output:

Input:

Enter the number of students: 2

Enter details for student 1:

Name: Alice

Marks: 85.5

Enter details for student 2:

Name: Bob

Marks: 90.0

File Content (students_sequential.txt):

Alice 85.50
Bob 90.00

Output:

Student data has been written to 'students_sequential.txt'.

Reading data from the file sequentially:

---------------------------------------

Name: Alice, Marks: 85.50

Name: Bob, Marks: 90.00

Key Points:

Sequential Access:

Data is processed in order, making it simple and efficient for linear operations.

File Handling Functions:

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.

You might also like