0% found this document useful (0 votes)
33 views16 pages

Unit V

The document provides detailed notes on file processing in C, covering topics such as file definitions, types, handling functions, sequential and random access, and command line arguments. It explains how files are used for data storage, the differences between sequential and random access methods, and includes example code for various file operations. The conclusion emphasizes the importance of file processing for efficient data management in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views16 pages

Unit V

The document provides detailed notes on file processing in C, covering topics such as file definitions, types, handling functions, sequential and random access, and command line arguments. It explains how files are used for data storage, the differences between sequential and random access methods, and includes example code for various file operations. The conclusion emphasizes the importance of file processing for efficient data management in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Here are detailed notes on UNIT V: File Processing for 15 Marks, based on the provided

topics:

1. Files in C (15 Marks)

Definition of Files in C:

 A file is a collection of related data stored on a secondary storage device, such as a


hard disk or solid-state drive (SSD).
 Files are used to store data persistently, meaning the data remains even after the
program terminates.
 C provides functions to handle files and perform various operations like reading,
writing, and closing files.

Types of Files in C:

1. Text Files:
o These are files in which data is stored as human-readable text. They are used
to store plain text.
o Operations on text files are done using fopen(), fread(), fwrite(),
fclose(), etc.
2. Binary Files:
o These are files where data is stored in a binary format. Binary files are used to
store structured data.
o Operations on binary files are done using fopen(), fread(), fwrite(),
fclose(), etc.

File Handling Functions in C:

 fopen(): Used to open a file.


 fclose(): Closes the opened file.
 fread(): Reads data from the file.
 fwrite(): Writes data to the file.
 fgetc(): Reads a single character from the file.
 fputc(): Writes a single character to the file.
 fprintf() / fscanf(): Used for formatted input and output operations.

File Modes:

 r: Open a file for reading.


 w: Open a file for writing (if file doesn’t exist, it is created).
 a: Open a file for appending.
 r+: Open a file for both reading and writing.
 w+: Open a file for both reading and writing (creates the file if it doesn't exist).
 a+: Open a file for reading and appending.

Example Code (Opening and Closing a File):


FILE *file = fopen("example.txt", "w");
if (file == NULL) {
printf("File could not be opened!\n");
return 1;
}
fprintf(file, "Hello, File Handling in C!\n");
fclose(file);

2. Types of File Processing: Sequential Access, Random Access (15 Marks)

Types of File Processing:

1. Sequential Access File Processing:


o Data is read or written in a sequential manner (one byte/record at a time).
o The file pointer moves in the order in which the data is written, i.e., the pointer
is moved to the next byte/record automatically after reading or writing.
o Ideal for applications where you process data in order, such as log files, text
files, etc.

Example Use Cases:

Reading data from a text file where each line is processed one by one.
o
Writing logs to a file where each log entry is appended.
o
2. Random Access File Processing:
o Allows you to read or write data at any position within the file, i.e., the file
pointer can be moved to any part of the file using fseek().
o It is more efficient for certain applications, such as databases or systems that
store records at arbitrary locations.

Example Use Cases:

o Database file management.


o Updating a specific record in the middle of the file.

Key Functions for Sequential Access:

 fgetc(): Read one character at a time from a file.


 fputc(): Write one character at a time to a file.

Key Functions for Random Access:

 fseek(): Move the file pointer to a specified position.


 ftell(): Return the current position of the file pointer.
 fread() / fwrite(): Read/write data in bulk.

Example Code (Sequential Access):

FILE *file = fopen("data.txt", "r");


if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
char ch;
while ((ch = fgetc(file)) != EOF) {
putchar(ch);
}
fclose(file);

Example Code (Random Access):

FILE *file = fopen("records.dat", "r+");


if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
fseek(file, sizeof(int) * 2, SEEK_SET); // Move to third record
int data;
fread(&data, sizeof(int), 1, file);
printf("Read data: %d\n", data);
fclose(file);

3. Sequential Access File (15 Marks)

Sequential Access File:

 In sequential access, the file is accessed from the beginning to the end in a linear
manner. The file pointer moves to the next record/byte after each read/write operation.
 This method is simple and easy to implement but inefficient for accessing specific
records in large files.

Characteristics:

 The file pointer automatically advances when data is read or written.


 Sequential access is suitable when all the data needs to be processed in order (e.g.,
reading or writing a list of records).
 In sequential access, data is read/written one item at a time.

Example Code (Sequential File Read/Write):

FILE *file = fopen("sequential.txt", "w+");


if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
fprintf(file, "Name: Alice\nAge: 30\n");
fprintf(file, "Name: Bob\nAge: 25\n");
fclose(file);

// Read from the file


file = fopen("sequential.txt", "r");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
char ch;
while ((ch = fgetc(file)) != EOF) {
putchar(ch);
}
fclose(file);

4. Random Access File (15 Marks)

Random Access File:

 Random access allows you to move the file pointer directly to any part of the file
without having to read through the file sequentially.
 This access method is useful for applications where records can be randomly
accessed, such as in databases or file systems.

Characteristics:

 You can access any part of the file at any time, making it more efficient than
sequential access for specific read/write operations.
 Uses fseek() to move the pointer and ftell() to find the current pointer position.

Example Code (Random Access File Writing):

FILE *file = fopen("random_access.dat", "w+");


if (file == NULL) {
printf("Error opening file!\n");
return 1;
}

struct Record {
int id;
char name[20];
};

struct Record record1 = {1, "Alice"};


struct Record record2 = {2, "Bob"};

fseek(file, 0, SEEK_SET);
fwrite(&record1, sizeof(struct Record), 1, file);
fseek(file, sizeof(struct Record), SEEK_SET); // Move to the second record
fwrite(&record2, sizeof(struct Record), 1, file);

fclose(file);

5. Command Line Arguments (15 Marks)

Command Line Arguments:

 Command line arguments are passed to a C program at the time of execution via the
terminal. The arguments are passed as an array of strings (argv[]), and the number of
arguments is stored in argc.
 argc holds the number of arguments passed to the program (including the program
name itself).
 argv[] is an array of strings containing each argument passed from the command
line.

How to Use Command Line Arguments:

 The program can use argc to check how many arguments were passed, and then use
argv[] to access each argument.
 Command line arguments are useful for passing file names, configuration settings, or
other parameters.

Example Code (Using Command Line Arguments):

#include <stdio.h>

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


if (argc != 3) {
printf("Usage: ./program <arg1> <arg2>\n");
return 1;
}

int num1 = atoi(argv[1]);


int num2 = atoi(argv[2]);
printf("The sum is: %d\n", num1 + num2);

return 0;
}

Conclusion

 File Processing in C involves working with files for storing and retrieving data.
 Sequential Access processes files line by line, making it simpler but less efficient for
random access needs.
 Random Access allows direct access to any part of the file, making it more efficient
for certain tasks, such as database management.
 Command Line Arguments enable flexible input from the user or other programs,
allowing your program to work with various inputs at runtime.

1. Files in C (15 Marks)

Concept:
Files are used to store data on a permanent basis. C provides standard library functions for
working with files: opening, reading, writing, and closing.

Example from Book:

 Example from T1, Chapter 15, pp. 420-440 (C Programming: "Programming in C"
by Reema Thareja)

Program (Write and Read to/from a File):


#include <stdio.h>

int main() {
FILE *file;
char str[] = "This is an example of file handling in C.";

// Opening the file in write mode


file = fopen("example.txt", "w");
if (file == NULL) {
printf("Error opening the file.\n");
return 1;
}

// Writing data to the file


fprintf(file, "%s", str);
fclose(file); // Closing the file

// Reading the data from the file


file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening the file.\n");
return 1;
}

// Displaying the content of the file


char ch;
while ((ch = fgetc(file)) != EOF) {
putchar(ch);
}
fclose(file);

return 0;
}

Explanation:

 The program writes a string to a file and then reads it back.


 fopen() is used to open the file, fprintf() writes data, and fgetc() reads character
by character.
 The file is closed using fclose() to save changes.

2. Types of File Processing: Sequential Access, Random Access (15 Marks)

Concept:

 Sequential Access processes the file one record at a time.


 Random Access allows direct access to any part of the file without sequential
traversal.

Example from Book:

 Example from R3, Chapter 11, pp. 500-520 (C Programming: "C How to Program"
by Deitel & Deitel)
Program (Sequential Access - Writing and Reading):

#include <stdio.h>

int main() {
FILE *file;
char text[] = "Sequential access example.\n";

// Writing data to a file using sequential access


file = fopen("sequential.txt", "w");
if (file == NULL) {
printf("Unable to open the file.\n");
return 1;
}
fprintf(file, "%s", text);
fclose(file); // Close the file after writing

// Reading from the file using sequential access


file = fopen("sequential.txt", "r");
if (file == NULL) {
printf("Unable to open the file.\n");
return 1;
}

// Reading and displaying the file's content


char ch;
while ((ch = fgetc(file)) != EOF) {
putchar(ch);
}
fclose(file); // Close the file after reading

return 0;
}

Program (Random Access - Modify Record):

#include <stdio.h>

struct Record {
int id;
char name[50];
};

int main() {
FILE *file;
struct Record record;

// Writing data to a file using random access


file = fopen("random.dat", "w+");
if (file == NULL) {
printf("Unable to open the file.\n");
return 1;
}

// Writing first record


record.id = 1;
strcpy(record.name, "John");
fwrite(&record, sizeof(struct Record), 1, file);

// Moving file pointer to modify a specific record (2nd record)


fseek(file, sizeof(struct Record), SEEK_SET);
record.id = 2;
strcpy(record.name, "Jane");
fwrite(&record, sizeof(struct Record), 1, file);

fclose(file); // Close after writing

// Reading data from the file using random access


file = fopen("random.dat", "r");
if (file == NULL) {
printf("Unable to open the file.\n");
return 1;
}

// Moving file pointer to the 2nd record


fseek(file, sizeof(struct Record), SEEK_SET);
fread(&record, sizeof(struct Record), 1, file);
printf("ID: %d, Name: %s\n", record.id, record.name);
fclose(file); // Close after reading

return 0;
}

Explanation:

 In sequential access, the data is read and written in order, one after the other.
 In random access, fseek() is used to move the pointer to a specific record, and
fread()/fwrite() allow direct reading and writing.

3. Sequential Access File (15 Marks)

Concept:
Sequential access is used when data needs to be processed in a sequential manner, such as
reading or writing records one by one.

Example from Book:

 Example from T1, Chapter 15, pp. 440-460 (C Programming: "Programming in C"
by Reema Thareja)

Program (Sequential Access - Process File Line by Line):

#include <stdio.h>

int main() {
FILE *file;
char line[100];

// Open file for writing using sequential access


file = fopen("sequential_example.txt", "w");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
fprintf(file, "Line 1: Hello, this is sequential access.\n");
fprintf(file, "Line 2: We process data one line at a time.\n");
fclose(file);

// Open file for reading


file = fopen("sequential_example.txt", "r");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}

// Read the file sequentially line by line


while (fgets(line, sizeof(line), file)) {
printf("%s", line);
}
fclose(file);

return 0;
}

Explanation:

 The program uses fprintf() to write lines to a file and fgets() to read lines from
the file sequentially.
 The pointer moves automatically to the next line after reading.

4. Random Access File (15 Marks)

Concept:
Random access allows reading and writing files at arbitrary positions using fseek(), making
it ideal for databases and large files that require frequent updates or lookups.

Example from Book:

 Example from R1, Chapter 10, pp. 550-575 (C Programming: "Let Us C" by
Yashwant Kanetkar)

Program (Random Access - Modify Specific Record):

#include <stdio.h>

struct Employee {
int id;
char name[50];
float salary;
};

int main() {
FILE *file;
struct Employee e;

// Open the file for random access (write mode)


file = fopen("employee.dat", "w+");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}

// Writing first employee record


e.id = 1;
strcpy(e.name, "Alice");
e.salary = 50000.0;
fwrite(&e, sizeof(struct Employee), 1, file);

// Moving the pointer to the second employee record


fseek(file, sizeof(struct Employee), SEEK_SET);
e.id = 2;
strcpy(e.name, "Bob");
e.salary = 55000.0;
fwrite(&e, sizeof(struct Employee), 1, file);

// Modify the second employee's salary using random access


fseek(file, sizeof(struct Employee), SEEK_SET); // Move to second
record
e.salary = 60000.0;
fwrite(&e, sizeof(struct Employee), 1, file); // Overwrite with updated
salary

fclose(file); // Close file after writing

// Reading data from the file using random access


file = fopen("employee.dat", "r");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}

fseek(file, sizeof(struct Employee), SEEK_SET); // Move to second


record
fread(&e, sizeof(struct Employee), 1, file);
printf("Employee ID: %d, Name: %s, Salary: %.2f\n", e.id, e.name,
e.salary);

fclose(file);

return 0;
}

Explanation:

 The program writes and updates specific records in the file using random access.
fseek() is used to move the pointer to the desired position, and fwrite() is used to
overwrite the record.

5. Command Line Arguments (15 Marks)

Concept:
Command line arguments are parameters passed to the program when it is executed. These
arguments are used to provide input values to the program, like filenames or numerical data.
Example from Book:

 Example from T1, Chapter 15, pp. 460-470 (C Programming: "Programming in C"
by Reema Thareja)

Program (Command Line Arguments - Sum of Two Numbers):

#include <stdio.h>
#include <stdlib.h>

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


if (argc != 3) {
printf("Usage: ./program <num1> <num2>\n");
return 1;
}

int num1 = atoi(argv[1]);


int num2 = atoi(argv[2]);
int sum = num1 + num2;
printf("The sum is: %d\n", sum);

return 0;
}

Explanation:

 The program takes two command line arguments, converts them to integers using
atoi(), and calculates their sum. If the user doesn't provide the correct number of
arguments, it displays a usage message.

Here are the technical interview questions along with their answers, company names, and
years, based on the topics of File Processing in C (Sequential Access, Random Access,
Command Line Arguments):

1. Files in C

Question:

Explain how file handling works in C. What are the common file modes used in C, and
how do you open and close files?

Answer:

File handling in C involves reading from and writing to files stored on secondary storage
(e.g., hard drives). Common functions used in file handling are:

 fopen(): Opens a file.


 fclose(): Closes the file.
 fread(): Reads data from the file.
 fwrite(): Writes data to the file.
 fgetc(): Reads a single character from the file.
 fputc(): Writes a single character to the file.
 fprintf(): Writes formatted data to the file.

File Modes:

 r: Open a file for reading.


 w: Open a file for writing (creates the file if it doesn't exist).
 a: Open for appending (creates the file if it doesn't exist).
 r+: Open for both reading and writing.
 w+: Open for both reading and writing (creates the file if it doesn't exist).
 a+: Open for both reading and appending.

Example Code:

FILE *file = fopen("example.txt", "w");


if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
fprintf(file, "Hello, World!\n");
fclose(file);
Company: Infosys
Year: 2018

2. Types of File Processing: Sequential Access, Random Access

Question:

What is the difference between sequential access and random access file processing in
C? Explain with an example.

Answer:

Sequential Access:

 Data is read or written one record at a time in the order it appears in the file.
 The file pointer moves automatically after each read or write operation.

Random Access:

 Data can be accessed directly at any position in the file using fseek().
 It is used for tasks like databases where you need to access or modify specific records.

Example for Sequential Access:

FILE *file = fopen("sequential.txt", "r");


char ch;
while ((ch = fgetc(file)) != EOF) {
putchar(ch);
}
fclose(file);

Example for Random Access:

FILE *file = fopen("random.dat", "r+");


fseek(file, 2 * sizeof(int), SEEK_SET); // Move to the second record
int data;
fread(&data, sizeof(int), 1, file);
printf("Data: %d\n", data);
fclose(file);
Company: Cognizant
Year: 2020

3. Sequential Access File

Question:

What is sequential access file processing in C? How would you implement a program to
read data from a sequential file?

Answer:

Sequential Access File:

 Data is processed in a linear order.


 The file pointer moves automatically after each operation.

Example Code (Reading from a Sequential File):

#include <stdio.h>

int main() {
FILE *file;
char line[100];

// Open file for writing using sequential access


file = fopen("sequential_example.txt", "w");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}

fprintf(file, "Line 1: Hello, this is sequential access.\n");


fprintf(file, "Line 2: We process data one line at a time.\n");
fclose(file);

// Open file for reading


file = fopen("sequential_example.txt", "r");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
// Read the file sequentially line by line
while (fgets(line, sizeof(line), file)) {
printf("%s", line);
}
fclose(file);

return 0;
}
Company: TCS
Year: 2021

4. Random Access File

Question:

Explain random access file processing in C. How can you modify specific records in a
file using random access?

Answer:

Random Access allows you to move the file pointer to any position within the file using
fseek(). This is useful for updating or reading specific records.

Key Functions:

 fseek(): Moves the file pointer.


 fread() / fwrite(): Reads or writes data at a specific position in the file.

Example Code (Modifying a Record in a Random Access File):

#include <stdio.h>
#include <string.h>

struct Employee {
int id;
char name[50];
float salary;
};

int main() {
FILE *file;
struct Employee e;

// Open the file for both reading and writing


file = fopen("employee.dat", "r+");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}

// Move file pointer to the second record


fseek(file, sizeof(struct Employee), SEEK_SET);
// Update the second record
e.salary = 75000.0;
fwrite(&e, sizeof(struct Employee), 1, file);

fclose(file); // Close after writing


return 0;
}
Company: Wipro
Year: 2022

5. Command Line Arguments

Question:

What are command line arguments in C? How can you pass arguments to a C program
and use them in the program?

Answer:

Command Line Arguments are parameters passed to the program at runtime. They are
passed to the program through the terminal and accessed using the argc (argument count)
and argv[] (argument vector) variables.

argc: The number of arguments passed to the program (including the program name).
argv[]: An array of strings containing the arguments passed.

Example Code (Adding Two Numbers Using Command Line Arguments):

#include <stdio.h>
#include <stdlib.h>

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


if (argc != 3) {
printf("Usage: ./program <num1> <num2>\n");
return 1;
}

int num1 = atoi(argv[1]); // Convert string to integer


int num2 = atoi(argv[2]);
printf("Sum of %d and %d is: %d\n", num1, num2, num1 + num2);

return 0;
}

Explanation:

 The program expects two command-line arguments (numbers). The atoi() function is used
to convert these arguments from strings to integers.
 The program calculates and prints the sum of the two numbers.

Company: Accenture
Year: 2021

You might also like