0% found this document useful (0 votes)
1 views18 pages

c File Handling Assignment

This document is an assignment on file handling in C programming, submitted by Ishan Panta to St. Xavier's College. It includes a detailed explanation of file concepts, handling modes, types of files, and various file handling functions, along with multiple C programming exercises demonstrating file operations. The assignment covers creating, reading, writing, and manipulating files, including operations on employee records.

Uploaded by

chhetriishan57
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)
1 views18 pages

c File Handling Assignment

This document is an assignment on file handling in C programming, submitted by Ishan Panta to St. Xavier's College. It includes a detailed explanation of file concepts, handling modes, types of files, and various file handling functions, along with multiple C programming exercises demonstrating file operations. The assignment covers creating, reading, writing, and manipulating files, including operations on employee records.

Uploaded by

chhetriishan57
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

ST.

XAVIER’S COLLEGE
MAITIGHAR, KATHMANDU
PHONE: 01-5344636,01-5321365
EMAIL: ktm@[Link]

ASSIGNMENT NUMBER – 03
C PROGRAMMING FILE

Submitted by: Submitted to: Signature


Name:Ishan Panta Department of Computer Science
Roll no: 809 [Link]’s College
Class:12
Section: H

Date : august 2nd ,2026


Part I File Handling in C ...............................................................................................1
1. Define file. Why do we need file handling concept in programming? ..............1
2. Explain the various file handling modes in C. ...................................................1
3. Explain the types of files in file handling. ......................................................... 2
4. List out the various file handling functions in C with its purpose and syntax. ..3
1. Write a C program to create a new data file and store a character in it using
fputc(). Read the character afterwards using fgetc(). .............................................4
2. Write a C program to create a new data file and store an integer in it using
fputw(). Read the integer afterwards using fgetw(). .............................................. 4
3. Write a C program to create a new data file and store a string in it using fputs().
Read the string afterwards using fgets(). ....................................................................... 5
4. Write a C program to create a new data file and store a sentence “I love C
programming.”using fwrite(). Read the file afterwards using fread() upto 8 characters
only. ............................................................................................................................... 6
5. Write a C program to store Name, Address, Age and Salary of 10 employees in a
data file [Link]. ....................................................................................................6
6. Write a C program to display the records whose salary is greater than 15000 and
who is younger than 25 from the data file [Link] created in Q5. Display the
records in properformat. ................................................................................................ 9
7. Write a C program to add two new records of employees in [Link] created in
Q5. ................................................................................................................................10
8 . Write a C program to read the [Link] file created in Q5 and save the records
of employees with Address “kathmandu” in a new [Link] file. ..........11
9. Write a C program to display the records of the [Link] file created
in Q8 and rename it with [Link] filename. ................................ 12
10. Write a program to count the number of characters in a file you have created. .... 13
11. Write a C program to read character of 10th position and display it using fseek(),
ftell(), frewind() functions. .......................................................................................... 14
12. Write a C program to delete the file [Link] from Q9. ..........15
Conclusion ................................................................................................................... 16
Part I File Handling in C

1. Define file. Why do we need file handling concept in


programming?
Definition of a File
A file is a collection of related data or information stored together as a single unit on a
secondary storage device, such as a hard disk. Every file is identified by a unique
name (filename) and, in C, is accessed and manipulated using a pointer of type FILE.
Need for File Handling
In normal programs, data entered by the user or generated during execution is stored
in variables, which reside in primary memory (RAM). This data is temporary and is
lost as soon as the program terminates or the computer is switched off. File handling
solves this problem and provides several advantages:
● Permanent storage: Data can be stored permanently on a secondary storage
device and retrieved whenever required, even after the program ends.
● Reusability: Data stored in a file can be reused by the same program or by
different programs without re-entering it.
● Large volume of data: Files can store a large amount of data that cannot
conveniently be handled using variables and arrays alone.
● Time saving: Since data is already stored, time and effort needed to re-enter
data every time the program runs is saved.
● Data transfer: Files make it easy to transfer data from one computer/program
to another.
● Data security and backup: Files allow data to be backed up and protected
using techniques like passwords and permissions.

2. Explain the various file handling modes in C.

When a file is opened using fopen(), it must be opened in a specific mode that defines
the type of operations (read, write, append, etc.) that can be performed on it. The
commonly used file modes in C are:
r (Read)
Opens an existing text file for reading only. If the file does not exist, fopen() returns
NULL.
w (Write)
Opens a text file for writing. If the file already exists, its contents are overwritten
(truncated to zero length); if it does not exist, a new file is created.
a (Append)

1
Opens a text file for writing at the end of the file. Data is added after the existing
content. If the file does not exist, a new file is created.
r+ (Read/Write)
Opens an existing text file for both reading and writing. The file must already exist.
w+ (Write/Read)
Creates a new file for both reading and writing. If the file exists, its previous contents
are erased.
a+ (Append/Read)
Opens a file for both reading and appending. Existing data is preserved and new data
is written at the end; if the file does not exist, it is created.
Binary Modes
Adding 'b' to any of the above modes (rb, wb, ab, rb+, wb+, ab+) opens the file in
binary mode instead of the default text mode, which is used for handling non-text data
such as images, audio, or structured records.

3. Explain the types of files in file handling.

Files used in file handling are broadly classified into two types based on how data is
stored and accessed:
1. Text Files
A text file stores data in the form of ASCII characters, where each line of text is
terminated by a special character called the End of Line (EOL), and the end of the file
is marked by an End of File (EOF) character. Text files are human-readable, can be
opened and edited with a simple text editor, and are generally used for storing simple,
small amounts of character-based data. Examples include .txt files and C source code
files (.c).
2. Binary Files
A binary file stores data in the same binary format (0s and 1s) in which it is held in
memory, without any translation. Binary files are not human-readable in a text editor,
are more compact and faster to read/write than text files, and are typically used to
store structured data such as records, images, audio, or executable programs.
Examples include .bin, .exe, and .dat files.
On the Basis of Access, Files Can Also Be Categorized As:
● Sequential Access Files: Data is read or written in a linear, sequential order
from the beginning to the end of the file.
● Random Access Files: Data can be read or written directly at any position in
the file using functions like fseek(), without reading through preceding data.

2
4. List out the various file handling functions in C with its
purpose and syntax.
Some of the commonly used file handling functions available in the C standard library
(stdio.h) are listed below, along with their purpose and syntax:
fopen()
Purpose: Opens a file and returns a FILE pointer used for further operations.
Syntax: FILE *fopen(const char *filename, const char *mode);
fclose()
Purpose: Closes an opened file and frees the associated resources.
Syntax: int fclose(FILE *fptr);
fprintf()
Purpose: Writes formatted data to a file.
Syntax: int fprintf(FILE *fptr, "format", args...);
fscanf()
Purpose: Reads formatted data from a file.
Syntax: int fscanf(FILE *fptr, "format", &args...);
getc()
Purpose: Reads a single character from a file.
Syntax: int getc(FILE *fptr);
putc()
Purpose: Writes a single character to a file.
Syntax: int putc(int char, FILE *fptr);
fgets()
Purpose: Reads a line (string) from a file.
Syntax: char *fgets(char *str, int n, FILE *fptr);
fputs()
Purpose: Writes a string to a file.
Syntax: int fputs(const char *str, FILE *fptr

3
1. Write a C program to create a new data file and store a
character in it using fputc(). Read the character afterwards using
fgetc().

#include <stdio.h>

int main() {
printf("program executed by Ishan Panta\n");

FILE *fp = fopen("[Link]", "w");


char ch = 'A';
fputc(ch, fp);
fclose(fp);

fp = fopen("[Link]", "r");
ch = fgetc(fp);
printf("Character read: %c\n", ch);
fclose(fp);

return 0;
}

2. Write a C program to create a new data file and store an


integer in it using fputw(). Read the integer afterwards using
fgetw().

#include <stdio.h>

int main() {
printf("program executed by Ishan Panta\n");

FILE *fp = fopen("[Link]", "w");


int num = 12345;
putw(num, fp);
fclose(fp);

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

4
printf("Integer read: %d\n", num);
fclose(fp);

return 0;
}

3. Write a C program to create a new data file and store a


string in it using fputs(). Read the string afterwards using
fgets().

#include <stdio.h>

int main() {
printf("program executed by Ishan Panta\n");

FILE *fp = fopen("[Link]", "w");


fputs("Hello World", fp);
fclose(fp);

char str[100];
fp = fopen("[Link]", "r");
fgets(str, 100, fp);
printf("String read: %s\n", str);
fclose(fp);

return 0;
}

5
4. Write a C program to create a new data file and store a
sentence “I love C programming.”using fwrite(). Read
the file afterwards using fread() upto 8 characters only.

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

int main() {
printf("program executed by Ishan Panta\n");

char sentence[] = "I love C programming.";


FILE *fp = fopen("[Link]", "w");
fwrite(sentence, sizeof(char), strlen(sentence), fp);
fclose(fp);

char buffer[9] = "";


fp = fopen("[Link]", "r");
fread(buffer, sizeof(char), 8, fp);
buffer[8] = '\0';
printf("Read (8 chars): %s\n", buffer);
fclose(fp);

return 0;
}

5. Write a C program to store Name, Address, Age and


Salary of 10 employees in a data file [Link].

#include <stdio.h>

struct Employee {

6
char name[30];
char address[30];
int age;
float salary;
};

int main() {
printf("program executed by Ishan Panta\n");
int i;
struct Employee emp;
FILE *fp = fopen("[Link]", "w");

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


printf("\nEnter details of employee %d\n", i + 1);
printf("Name: ");
scanf("%s", [Link]);
printf("Address: ");
scanf("%s", [Link]);
printf("Age: ");
scanf("%d", &[Link]);
printf("Salary: ");
scanf("%f", &[Link]);

fwrite(&emp, sizeof(emp), 1, fp);


}

fclose(fp);
printf("\n10 employee records stored in [Link]\n");
return 0;
}

7
8
6. Write a C program to display the records whose salary
is greater than 15000 and who is younger than 25 from
the data file [Link] created in Q5. Display the
records in proper
format.

#include <stdio.h>

struct Employee {
char name[30];
char address[30];
int age;
float salary;
};

int main() {
printf("program executed by Ishan Panta\n");

struct Employee emp;


FILE *fp = fopen("[Link]", "r");
if (fp == NULL) {
printf("File not found\n");
return 1;
}

printf("%-20s%-20s%-10s%-10s\n", "Name", "Address", "Age", "Salary");


while (fread(&emp, sizeof(emp), 1, fp) == 1) {
if ([Link] > 15000 && [Link] < 25) {
printf("%-20s%-20s%-10d%-10.2f\n", [Link], [Link], [Link],
[Link]);
}
}

fclose(fp);
return 0;
}

9
7. Write a C program to add two new records of
employees in [Link] created in Q5.

#include <stdio.h>

struct Employee {
char name[30];
char address[30];
int age;
float salary;
};

int main() {
printf("program executed by Ishan Panta\n");
int i;
struct Employee emp;
FILE *fp = fopen("[Link]", "a");

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


printf("\nEnter details of new employee %d\n", i + 1);
printf("Name: ");
scanf("%s", [Link]);
printf("Address: ");
scanf("%s", [Link]);
printf("Age: ");
scanf("%d", &[Link]);
printf("Salary: ");
scanf("%f", &[Link]);

fwrite(&emp, sizeof(emp), 1, fp);


}

fclose(fp);
printf("\n2 new records added to [Link]\n");
return 0;
}

10
8 . Write a C program to read the [Link] file
created in Q5 and save the records of employees with
Address “kathmandu” in a new [Link]
file.
#include <stdio.h>
#include <string.h>

struct Employee {
char name[30];
char address[30];
int age;
float salary;
};

int main() {
printf("program executed by Ishan Panta\n");

struct Employee emp;


FILE *fp = fopen("[Link]", "r");
FILE *fk = fopen("[Link]", "w");

while (fread(&emp, sizeof(emp), 1, fp) == 1) {


if (strcmp([Link], "kathmandu") == 0) {
fwrite(&emp, sizeof(emp), 1, fk);
}

11
}

fclose(fp);
fclose(fk);
printf("Kathmandu records saved in [Link]\n");
return 0;
}

9. Write a C program to display the records of the


[Link] file created in Q8 and rename it
with [Link] filename.
#include <stdio.h>

struct Employee {
char name[30];
char address[30];
int age;
float salary;
};

int main() {
printf("program executed by Ishan Panta\n");

struct Employee emp;


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

printf("%-20s%-20s%-10s%-10s\n", "Name", "Address", "Age", "Salary");


while (fread(&emp, sizeof(emp), 1, fp) == 1) {
printf("%-20s%-20s%-10d%-10.2f\n", [Link], [Link], [Link],
[Link]);
}
fclose(fp);

rename("[Link]", "[Link]");
printf("\nFile renamed to [Link]\n");

return 0;
}

12
10. Write a program to count the number of characters in
a file you have created.

#include <stdio.h>

int main() {
printf("program executed by Ishan Panta\n");

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


int count = 0;
char ch;

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


count++;
}

fclose(fp);
printf("Number of characters: %d\n", count);
return 0;
}

13
11. Write a C program to read character of 10th position
and display it using fseek(), ftell(), frewind() functions.

#include <stdio.h>

int main() {
printf("program executed by Ishan Panta\n");

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


char ch;

fseek(fp, 9, SEEK_SET);
printf("Position (ftell): %ld\n", ftell(fp));

ch = fgetc(fp);
printf("10th character: %c\n", ch);

rewind(fp);
printf("Position after rewind: %ld\n", ftell(fp));

fclose(fp);
return 0;
}

14
12. Write a C program to delete the file
[Link] from Q9.
#include <stdio.h>

int main() {
printf("program executed by Ishan Panta\n");

if (remove("[Link]") == 0) {
printf("[Link] deleted successfully\n");
} else {
printf("Error deleting file\n");
}

return 0;
}

15
Conclusion

This lab assignment helped me gain a clear understanding of file handling


in C. I learned to use functions such as fputc and fgetc, putw and getw,
and fputs and fgets for handling characters, integers, and strings in files. I
also learned how fwrite and fread can be used to store and retrieve
structured data. Working with employee records taught me how to filter
data based on given conditions, append new records to an existing file,
extract specific records into a new file, rename files, and delete files. In
addition, I learned how to use fseek, ftell, and rewind to move to and
identify positions within a file. Overall, this assignment improved my
practical knowledge of how C programs create, read, modify, and manage
data stored in files.

16

You might also like