0% found this document useful (0 votes)
47 views

Unit-5(Part-3)File Handling in C

Uploaded by

rameshjaiswal365
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

Unit-5(Part-3)File Handling in C

Uploaded by

rameshjaiswal365
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Unit-5(Part-3)File Handling in C

Unit-5
File Handling in C
WHAT IS FILE?
File is a collection of bytes that is stored on secondary storage devices like disk. There are two kinds of files
in a system. They are,

1. Text files (ASCII)


2. Binary files
 Text files contain ASCII codes of digits, alphabetic and symbols.
 Binary file contains collection of bytes (0’s and 1’s). Binary files are compiled version of text
files.
Note-:
In programming, we may require some specific input data to be generated several numbers of times.
Sometimes, it is not enough to only display the data on the console. The data to be displayed may be very
large, and only a limited amount of data can be displayed on the console, and since the memory is volatile, it
is impossible to recover the programmatically generated data again and again. However, if we need to do so,
we may store it onto the local file system which is volatile and can be accessed every time. Here, comes the
need of file handling in C.

Why files are needed?


 When a program is terminated, the entire data is lost. Storing in a file will
preserve your data even if the program terminates.
 If you have to enter a large number of data, it will take a lot of time to enter
them all.
 However, if you have a file containing all the data, you can easily access the
contents of the file using a few commands in C.
 You can easily move your data from one computer to another without any
changes.

File handling in C enables us to create, update, read, and delete the files stored on the local file system
through our C program. The following operations can be performed on a file.

 Creation of the new file

 Opening an existing file

 Reading from the file

 Writing to the file

 Deleting the file

1
Unit-5(Part-3)File Handling in C

Functions for file handling


There are many functions in the C library to open, read, write, search and
close the file. A list of file functions are given below:

No. Function Description

1 fopen() opens new or existing file

2 fprintf() write data into the file

3 fscanf() reads data from the file

4 fputc() writes a character into the file

5 fgetc() reads a character from file

6 fclose() closes the file

7 fseek() sets the file pointer to given position

8 fputw() writes an integer to file

9 fgetw() reads an integer from file

10 ftell() returns current position

11 rewind() sets the file pointer to the beginning of the file

Steps for processing a File


 Declare a file pointer variable.
 Open a file using fopen() function.
 Process the file using the suitable function.
 Close the file using fclose() function.
Opening File: fopen()
We must open a file before it can be read, write, or update. The fopen()
function is used to open a file. The syntax of the fopen() is given below.

2
Unit-5(Part-3)File Handling in C

FILE *fopen( const char * filename, const char * mode );


The fopen() function accepts two parameters:

o The file name (string). If the file is stored at some specific location, then
we must mention the path at which the file is stored. For example, a file
name can be like "c://some_folder/some_file.ext".
o The mode in which the file is to be opened. It is a string.

We can use one of the following modes in the fopen() function.

Mode Description

R opens a text file in read mode

W opens a text file in write mode

A opens a text file in append mode

r+ opens a text file in read and write mode

w+ opens a text file in read and write mode

a+ opens a text file in read and write mode

Rb opens a binary file in read mode

Wb opens a binary file in write mode

Ab opens a binary file in append mode

rb+ opens a binary file in read and write mode

wb+ opens a binary file in read and write mode

ab+ opens a binary file in read and write mode

The fopen function works in the following way.


3
Unit-5(Part-3)File Handling in C

o Firstly, It searches the file to be opened.


o Then, it loads the file from the disk and place it into the buffer. The
buffer is used to provide efficiency for the read operations.
o It sets up a character pointer which points to the first character of the
file.

Closing File: fclose()


The fclose() function is used to close a file. The file must be closed after
performing all the operations on it. The syntax of fclose() function is given
below

int fclose( FILE *fp );

C fprintf() and fscanf()

Writing File : fprintf() function


The fprintf() function is used to write set of characters into file. It sends formatted
output to a stream.

Syntax:

int fprintf(FILE *stream, const char *format [, argument, ...])


Example

#include <stdio.h>
main()
{
FILE *fp;
fp = fopen("file.txt", "w");//opening file
fprintf(fp, "Hello file by fprintf...\n");//writing data into file
fclose(fp);//closing file
}

Reading File : fscanf() function


The fscanf() function is used to read set of characters from file. It reads a word from
4
Unit-5(Part-3)File Handling in C

the file and returns EOF at the end of file.

Syntax

int fscanf(FILE *stream, const char *format [, argument, ...])


Example

#include <stdio.h>
main(){
FILE *fp;
char buff[255];//creating char array to store data of file
fp = fopen("file.txt", "r");
while(fscanf(fp, "%s", buff)!=EOF){
printf("%s ", buff );
}
fclose(fp);
}
Output:

Hello file by fprintf...

Writing and Reading


#include <stdio.h>
main()
{
FILE *fp;
char buff[255];//creating char array to store data of file

fp = fopen("file.txt", "w");//opening file


fprintf(fp, "This is my first file\n");//writing data into file
fclose(fp);//closing file
fp = fopen("file.txt", "r");
while(fscanf(fp, "%s", buff)!=EOF){
printf("%s ", buff );

5
Unit-5(Part-3)File Handling in C

}
fclose(fp);
}

C File Example: Storing employee information


Let's see a file handling example to store employee information as entered by user
from console. We are going to store id, name and salary of the employee

#include <stdio.h>
void main()
{
FILE *fptr;
int id;
char name[30];
float salary;
fptr = fopen("emp.txt", "w+");/* open for writing */
if (fptr == NULL)
{
printf("File does not exists \n");
return;
}
printf("Enter the id\n");
scanf("%d", &id);
fprintf(fptr, "Id= %d\n", id);
printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr, "Name= %s\n", name);
printf("Enter the salary\n");
scanf("%f", &salary);
fprintf(fptr, "Salary= %.2f\n", salary);
fclose(fptr);
}
6
Unit-5(Part-3)File Handling in C

Output:

Enter the id
1
Enter the name
sonoo
Enter the salary
120000
Now open file from current directory. For windows operating system, go to TC\bin
directory, you will see emp.txt file. It will have following information.

Writing File : fputc() function


The fputc() function is used to write a single character into file. It outputs a
character to a stream.

Syntax:

int fputc(int c, FILE *stream)


Example:
#include <stdio.h>
main()
{
FILE *fp;
fp = fopen("file1.txt", "w");//opening file
fputc('a',fp);//writing single character into file
fclose(fp);//closing file
}
Reading File : fgetc() function
The fgetc() function returns a single character from the file. It gets a character
from the stream. It returns EOF at the end of file.

Syntax:

int fgetc(FILE *stream)


Example:

7
Unit-5(Part-3)File Handling in C

#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
char c;
clrscr();
fp=fopen("myfile.txt","r");

while((c=fgetc(fp))!=EOF){
printf("%c",c);
}
fclose(fp);
getch();
}
C fputs() and fgets()
The fputs() and fgets() in C programming are used to write and read string
from stream. Let's see examples of writing and reading file using fgets() and
fgets() functions.

Writing File : fputs() function


The fputs() function writes a line of characters into file. It outputs string to a
stream.

Syntax:

int fputs(const char *s, FILE *stream)


#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
clrscr();

fp=fopen("myfile2.txt","w");
fputs("hello c programming",fp);

8
Unit-5(Part-3)File Handling in C

fclose(fp);
getch();
}
myfile2.txt

hello c programming

Reading File : fgets() function


The fgets() function reads a line of characters from file. It gets string from a
stream.

Syntax

char* fgets(char *s, int n, FILE *stream)


Example:

#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
char text[300];
clrscr();

fp=fopen("myfile2.txt","r");
printf("%s",fgets(text,200,fp));

fclose(fp);
getch();
}
Output:

hello c programming
Output:
Enter character: a
9
Unit-5(Part-3)File Handling in C

Character entered: a

1) EOF:
EOF stands for End of File. The function getc() returns EOF, on success.

2) putw() function:
The putw() function is used to write integers to the file.

Syntax of putw() function


putw(int number, FILE *fp);

The putw() function takes two arguments, first is an integer value to be written to
the file and second is the file pointer where the number will be written.

3) getw() function:
The getw() function is used to read integer value form the file.

Syntax of getw() function


int getw(FILE *fp);

10
Unit-5(Part-3)File Handling in C

The getw() function takes the file pointer as argument from where the integer value
will be read and returns returns the end-of-file if it has reached the end of file.

4) fscanf() function:
The fscanf() function is used to read set of characters from file. It reads a
word from the file and returns EOF at the end of file.
Syntax:
int fscanf(FILE *stream, const char *format [, argument, ...])
Example:
#include <stdio.h>
main(){
FILE *fp;
char b[255];//creating char array to store data of file
fp = fopen("file.txt", "r");
while(fscanf(fp, "%s", b)!=EOF){
printf("%s", b);
}
fclose(fp);
}

5) fprintf() function:
The fprintf() function is used to write set of characters into file. It sends
formatted output to a stream.
Syntax:
int fprintf(FILE *stream, const char *format [, argument, ...])

Example:
#include <stdio.h>
main(){
FILE *fp;
fp = fopen("file.txt", "w");//opening file
fprintf(fp, "Hello file by fprintf...\n");//writing data into file
fclose(fp);//closing file
}
Output:
Hello file by fprintf...

11
Unit-5(Part-3)File Handling in C

Example: Storing employee information


Let's see a file handling example to store employee information as entered by user from
console. We are going to store id, name and salary of the employee.

#include <stdio.h>
void main()
{
FILE *fptr;
int id;
char name[30];
float salary;
fptr = fopen("emp.txt", "w+");/* open for writing */
if (fptr == NULL)
{
printf("File does not exists \n");
return;
}
printf("Enter the id\n");
scanf("%d", &id);
fprintf(fptr, "Id= %d\n", id);
printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr, "Name= %s\n", name);
printf("Enter the salary\n");
scanf("%f", &salary);
fprintf(fptr, "Salary= %.2f\n", salary);
fclose(fptr);
}
Output:
Enter the id
1
Enter the name
sonoo
Enter the salary
120000

12
Unit-5(Part-3)File Handling in C

File Handling Program


1) /*C program to read data from keyboard and write it to a text file
*/
#include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
char ch;
FILE *fptr;
clrscr();
fptr=fopen("t3.txt","w");
if(fptr==NULL) {
printf("File can't be created");
getch();
exit(0);
}
printf("Enter some text and press enter key:\n");
while((ch=getchar())!=EOF) {
fputc(ch,fptr);
}
printf("\nFile created");
fclose(fptr);
getch();
}

2) /*C program to read data from a text file


*/
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
char ch;
FILE *fptr;
clrscr();

13
Unit-5(Part-3)File Handling in C

fptr=fopen("t4.txt","r");
if(fptr==NULL)
{
printf("\n File not available");
getch();
exit(0);
}
printf("\nContents of the File is:");
while((ch=fgetc(fptr))!=EOF) {
printf("%c",ch);
}
fclose(fptr);
getch();
}

3) /*C program to read integer numbers from a file named DATA and
then write all odd numbers to a file named ODD and all even
numbers to a file named EVEN*/
#include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
int a,n,i;
FILE *fp1,*fp2,*fp3;
clrscr();
fp1=fopen("DATA.txt","w");

if(fp1==NULL)
{
printf("File could not open!!");
getch();
exit(0);
}

printf("How many numbers?");


scanf("%d",&n);
printf("Enter contents of DATA file:\n");

14
Unit-5(Part-3)File Handling in C

for(i=0;i<n;++i)
{
scanf("%d",&a);

15
Unit-5(Part-3)File Handling in C

putw(a,fp1);
}

fclose(fp1);

fp1=fopen("DATA.txt","r");
fp2=fopen("ODD.txt","w");
fp3=fopen("EVEN.txt","w");

if(fp1==NULL||fp2==NULL||fp3==NULL)
{
printf("File could not open!!");
getch();
exit(0);
}

while((a=getw(fp1))!=EOF)
{
if(a%2!=0)
putw(a,fp2);
else
putw(a,fp3);
}

fclose(fp1);
fclose(fp2);
fclose(fp3);

fp2=fopen("ODD.txt","r");
fp3=fopen("EVEN.txt","r");

if(fp2==NULL||fp3==NULL)
{
printf("File could not open!!");
getch();
exit(0);
}

16
Unit-5(Part-3)File Handling in C

printf("\nContents of ODD file:\n");


while((a=getw(fp2))!=EOF)
printf("%d ",a);

printf("\nContents of EVEN file:\n");


while((a=getw(fp3))!=EOF)
printf("%d ",a);

fclose(fp2);
fclose(fp3);
getch();
}
Output:
How many numbers?10
Enter contents of DATA file:
1
2
3
4
5
6
7
8
9
10

Contents of ODD file:


13579
Contents of EVEN file:
2 4 6 8 10

17
Unit-5(Part-3)File Handling in C

4) /*C program to copy the contents of one file into another*/


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

void main()
{
FILE *fp1,*fp2;
char ch,f1[50],f2[50];
clrscr();

printf("Enter source file name(ex:source.txt): ");


scanf("%s",&f1);
printf("Enter destination file name(ex:destination.txt): ");
scanf("%s",&f2);

fp1=fopen(f1,"r");
fp2=fopen(f2,"w");

if(fp1==NULL||fp2==NULL)
{
printf("File could not open!!");
getch();
exit(0);
}

while((ch=getc(fp1))!=EOF) //getc() or fgetc()


putc(ch,fp2); //putc() or fputc()

fclose(fp1);
fclose(fp2);
printf("\n File copied successfully");
getch();
}

18

You might also like