Unit 5
Unit 5
C language provides a way to read or write the data from the secondary storage devices
in the form of file.
So far, we have learned many input/output library functions such as scanf(), gets(),
getch(), puts(), printf() etc. These functions operate on standard input device, keyboard
and standard output device, console. In program, data are stored in variables and
variables are a temporary storage. When program terminated the data stored in the
variables is lost.
In processing a large amount data, it is time consuming and difficult to handle the data
through input/output devices. We can store this data in a file and access it any time by
few commands provided by C language.
1. Naming a file
2. Opening a file
3. Reading from a file
4. Writing data into a file
5. Closing a file
Syntax# Example#
FILE *pointername FILE *ptr;
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
4.2 File operations
C language provides number of functions related with File operation.
Function Description
fopen() create a new file or open a existing file
fclose() closes a file
getc() reads a character from a file
putc() writes a character to a file
fscanf() reads a set of data from a file
fprintf() writes a set of data to a file
getw() reads a integer from a file
putw() writes a integer to a file
fseek() set the position to desire point
ftell() gives current position in the file
rewind() set the position to the begining point
4.1.1 Fopen()
The fopen() function opens a file and creates an instance of the FILE structure and
returns a pointer to that structure. This pointer is used with all subsequent file
operations in the program.
Syntax# Example#
FILE *fp;
FILE *fopen(char *filename, char
Fp = fopen(“xyz”, “w”);
*mode);
In the syntax, the name of file to be opened is pointed to by filename, how file is
accessed is pointed by mode.
Filename may have a path that specifies the drive or directory location where file is
stored. If the filename is specifying without a path, then file is assumed to be in the
current directory. If the filename is specified with path than double backslash (\\)
character is used to separate the directory. For example,D:\\jpp\\test.txt
mode Description
r opens a text file in reading mode
w opens or create a text file in writing mode.
a opens a text file in append mode
r+ opens a text file in both reading and writing mode
w+ opens a text file in both reading and writing mode
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
a+ opens a text file in both reading and writing mode
rb opens a binary file in reading mode
wb opens or create a binary file in writing mode
ab opens a binary file in append mode
rb+ opens a binary file in both reading and writing mode
wb+ opens a binary file in both reading and writing mode
ab+ opens a binary file in both reading and writing mode
Example#
If file does not open due to the following reason, NULL value is returned by fopen()
function.
FILE *fp;
fp = fopen(“abc.txt” , “w”);
if(fp== NULL)
{
printf(“\n file creating error”);
exit(1);
}
After finishing the operations on the file, file should be closed. Because during the file
operations file, pointer of FILE is associated with the file stream.
Syntax#
Syntax# Example#
int fclose(FILE *fp); FILE *fp;
fclose(fp);
It returns integer value either 0 on success or -1 on error during file close operation.
When the program terminates, all the file streams are automatically flushed and closed.
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
Character files stores every type of data in the form of character only. While binary files
store the data in a various type such as int, float, char etc.
C provides various built-in library functions for dealing with the file.
Text Binary
Text File can only contain textual data. Binary files typically contain a sequence
of bytes, or ordered groupings of
eight bits.
Less probability for corruption Probability for corruption
Text file formats may include only text Binary file formats may include multiple
data. types of data in the same file, such as
image, video, and audio data
Heavy weight in size. Light weight in size
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
4.4Input/output operations on text file
Character(text) files stores every type of data in the form of character only. C provides
functions to perform input/output operations on text file such as putc(), putw(),
getc(), getw(), fprintf(), fscanf(). These all functions are defined in stdio.h header
file.
4.4.1 putc()
This library function is used to write single character to the specified stream.
Syntax# Example#
int putc(char c, FILE *fp); putc(‘c’,fp);
#include<conio.h>
#include<stdio.h>
main()
{
FILE *f1;
clrscr();
f1=fopen("1.txt","w");
putc('a',f1);
fclose(f1);
getch();
Output#
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
When reading or writing a file, to detect that the file pointer is reached at the end of the
file, EOF is used.
In DOS, end of the file is indicated by a special character ctrl+z, in UNIX it is by ctrl+d.
4.4.3getc()
Syntax# Example#
int getc(FILE *fp); getc(fp);
Example# We have 1.txt file which contains some contents and now we are
trying to read it
#include<stdio.h>
#include<conio.h>
main()
{
FILE *f1;
char ch;
clrscr();
f1=fopen("1.txt","r");
while(ch!=EOF)
{
ch=getc(f1);
printf("%c",ch);
}
fclose(f1);
getch();
}
Output#
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
#include<conio.h>
#include<stdio.h>
main()
{
FILE *f1;
clrscr();
f1=fopen("11.txt","r");
if(f1 == NULL)
{
puts("\nDoes not exist\n");
exit( );
}
else
{
puts("\nFile is exist");
}
fclose(f1);
getch();
}
Output#
Does not exist
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
#include<stdio.h>
#include<conio.h>
main()
{
FILE *f1,*f2;
char ch;
clrscr();
f1=fopen("1.txt","r");
f2=fopen("2.txt","w");
while(ch!=EOF)
{
ch=getc(f1);
putc(ch,f2);
}
fclose(f1);
fclose(f2);
printf("\ncopied");
getch();
}
Output#
copied
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
Example# Read one file and divide vowels and consonants into other files
#include<stdio.h>
#include<conio.h>
main()
{
FILE *f1,*f2,*f3;
char ch;
clrscr();
f1=fopen("1.txt","r");
f2=fopen("v.txt","w");
f3=fopen("c.txt","w");
while(ch!=EOF)
{
ch=getc(f1);
if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u')
{
putc(ch,f2);
}
else
{
putc(ch,f3);
}
}
fclose(f1);
fclose(f2);
fclose(f3);
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
printf("\ncopied");
getch();
}
Output#
copied
#include<stdio.h>
#include<conio.h>
main()
{
FILE *f1;
char ch;
int line=0,space=0;
clrscr();
f1=fopen("1.txt","r");
while(ch!=EOF)
{
ch=getc(f1);
if(ch=='\n')
{
line++;
}
if(ch==' ')
{
space++;
}
}
fclose(f1);
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
getch();
}
Output#
No of Lines = 4
No of Spaces = 31
4.4.4 Rewind()
The rewind() function is used to move the cursor to the beginning of the file.
Syntax# Example#
void rewind(FILE *fp) rewind(*fp)
Example# Edit “1.txt” above file and append contents , rewind the cursor and
print all the contents
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
clrscr();
fp = fopen("1.txt","at+"); //append mode
fclose(fp);
getch();
}
Output#
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
Write some data :
Do you know the latest score or any update about match?
Hey Tell me Karan.
Ctrl+Z
Data in file :
India Vs Srilanka Match
Suranga Lakmal grabbed four wickets to help Sri Lanka bowl India out for 172.
Cheteshwar Pujara top scored with 52 for the hosts.
Follow live cricket score and updates.Do you know the latest score or any update
about match?
Hey Tell me Karan. //New contents added due to append mode
4.4.5 getw()
The getw() function is used to read integer value form the file.
The getw() function takes the file pointer as argument from where the integer value will
be read and returns the end-of-file if it has reached the end of file.
Syntax# Example#
int getw(FILE *fp) no=getw(f2)
4.4.6 putw()
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
The putw() function is used to write integers to the file.
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.
Syntax Example
putw(int number, FILE *fp); putw(22,f1);
#include<conio.h>
#include<stdio.h>
main()
{
int ar[10]={1,5,3,4,6,7,11,2,66,9};
FILE *f1,*f2;
int i,no;
clrscr();
f1=fopen("o.txt","w");
f2=fopen("e.txt","w");
for(i=0;i<10;i++)
{
if(ar[i]%2==0)
putw(ar[i],f2);
else
putw(ar[i],f1);
}
fclose(f1);
fclose(f2);
f1=fopen("o.txt","r");
while((no=getw(f1))!=EOF)
{
printf("\n%d",no);
}
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
fclose(f1);
printf("\n\nEven file \n\n");
f2=fopen("e.txt","r");
while((no=getw(f2))!=-1)
{
printf("\n%d",no);
}
fclose(f2);
getch();
}
Output#
Odd file
1
5
3
7
11
9
Even file
4
6
2
66
4.4.7fscanf()
This function is used to read different types of data from the file such
as int, float, char etc.
Syntax# Example#
fscanf(fp, “control string”, fscanf(f1,”%d %s”,no,name);
arguments list);
Control string is used to specify what types of data you want to read, Arguments list are
the lists of variables separated by comma. fp is the file pointer points to the file which
has been opened using fopen() function.
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
4.4.8 fprintf()
This function is used to write different types of data to the file such as int, float, char etc.
Syntax# Example#
fprintf(fp, “control string”, arguments fprintf(f1,”%s %d”,&no,&name);
list);
Control string is used to specify what types of data you want to read,
Arguments list are the lists of variables separated by comma. fp is the
file pointer points to the file which has been opened using fopen()
function.
Both functions fscanf() and fprintf() are used with binary data file.
Example# to read data from the keyboard and write to the file using fprintf()
function
#include<stdio.h>
#include<conio.h>
void main()
{
int rollno,semester;
char name[25], branch[25];
int total;
FILE *fp;
char filename[15];
clrscr();
fp=fopen(filename,"w");
if(fp==NULL)
{
printf("\n file can not open for writing");
}
printf("\n Enter rollno, name , branch details:");
scanf("%d %s %s",&rollno, &name,&branch);
printf("\n Enter semester and total marks:");
scanf("%d %d", &semester, &total);
fclose(fp);
getch();
}
Output#
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
Enter filename :f1.txt
Example# After adding record in above program , to read data from the file and
display to the file using fscanf() function
#include <stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
int rollno, semester;
char name[20], branch[20];
clrscr();
fp=fopen("f1.txt","r");
if(fp == NULL)
{
printf("Cannot open file.\n");
exit(1);
}
fclose(fp);
getch();
}
Output#
1 Vedika CE 1
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
Example# fprintf() and fscanf()
#include <stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
int rollno;
char name[20];
int i,n;
clrscr();
fp=fopen("f1.txt","w");
for(i=0;i<n;i++)
{
printf("\nEnter no=>");
scanf("%d",&rollno);
fflush(stdin);
printf("\nEnter name =>");
gets(name);
fprintf(fp,"\n%d %s",rollno,name);
}
fclose(fp);
fp=fopen("f1.txt","r");
printf(“\nRecords”);
for(i=0;i<n;i++)
{
fscanf(fp,"%d %s", &rollno, name);
printf("\n%d %s", rollno, name);
}
fclose(fp);
getch();
}
Output#
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
Enter no=>101
Enter no=>102
Enter no=>103
Records
101 Ram
102 Laxman
103 Yash
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
4.5Input/output operations on binary file
When a large amount of numerical data it to be stored, text mode will be insufficient
because memory occupation by it is large. In such case binary file is used. Working of
binary files is similar to text files with few differences in opening modes, reading from
file and writing to file. fread() and fwrite() functions are used with the binary file.
Opening a file
Binary file is open with same mode as with text file but character b is appended after the
mode such as wb, wb+, rb, rb+, ab, ab+ etc.
fread() function is used to read binary file and fwrite() function is used to write to the
binary file.
4.5.1 fwrite()
The fwrite() function is used to write records (sequence of bytes) to the file. A record
may be an array or a structure.
Syntax# Example#
fwrite( ptr, int size, int n, FILE *fp ); fwrite(&Stu1,sizeof(Stu1),1,fp);
4.5.2 fread()
4.5.3 fseek()
If we want to access the forty fourth record then first forty three records
read sequentially to reach forty four records. In random access data can
be accessed and processed directly.
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
access. C support fseek function for random access file.
fseek() function is used for setting the file position pointer at the specified bytes. fseek is
a function belonging to the ANCI C Standard Library and included in the file stdio.h. Its
purpose is to change the file position indicator for the specified stream.
Syntax# Example#
int fseek(FILE *stream_pointer, long fseek( fp, 7, SEEK_SET )
offset, int origin);
stream_pointer is a pointer to the stream FILE structure of which the position indicator
should be changed;
offset is a long integer which specifies the number of bytes from origin where the
position indicator should be placed;
#include<stdio.h>
#include<conio.h>
struct Student
{
int roll;
char name[25];
float marks;
};
void main()
{
FILE *fp;
char ch;
struct Student Stu;
clrscr();
fp = fopen("StudentR.dat","w"); //Creates
if(fp == NULL)
{
printf("\nCan't open file or file doesn't exist.");
exit(0);
}
do
{
printf("\nEnter RollNo => ");
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
scanf("%d",&Stu.roll);
fwrite(&Stu,sizeof(Stu),1,fp);
}while(ch=='y' || ch=='Y');
fclose(fp);
printf("\nRecords");
printf("\n\tRoll\tName\tMarks\n");
printf("\n===================================");
while(fread(&Stu,sizeof(Stu),1,fp)>0)
{
printf("\n\t%d\t%s\t%.2f",Stu.roll,Stu.name,Stu.marks);
}
printf("\n===================================");
fclose(fp);
getch();
}
Output#
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
Enter RollNo => 1
Enter Name => Ram
Enter Marks =>28
Records
Roll Name Marks
===================================
1 Ram 28.00
2 Mayur55.00
3 Vedika78.00
4 Mansi 39.00
5 Manav65.00
===================================
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct Student
{
int roll;
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
char name[25];
float marks;
};
void main()
{
int n;
FILE *fp;
struct Student s1;
clrscr();
fp=fopen("Studentr.dat","rb");
if (fp==NULL)
{
printf("\n error in opening file");
exit(1);
}
printf("\nEnter the record no to be read =>");
scanf("%d",&n);
fseek(fp,(n-1)*sizeof(s1),0);
fread(&s1,sizeof(s1),1,fp);
Output#
Roll no = 1
Name = Ram
Marks = 45.00
#include<stdio.h>
#include<conio.h>
struct Student
{
int roll;
char name[25];
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
float marks;
};
void writeRecord()
{
FILE *fp;
char ch;
struct Student Stu;
fp = fopen("StudentRec.dat","w");
if(fp == NULL)
{
printf("\nCan't open file or file doesn't exist.");
exit(0);
}
do
{
printf("\nEnter RollNo => ");
scanf("%d",&Stu.roll);
fwrite(&Stu,sizeof(Stu),1,fp);
}while(ch=='y' || ch=='Y');
void printRecord()
{
FILE *fp;
struct Student Stu;
fp = fopen("StudentRec.dat","r");
printf("\nRecords");
printf("\n\tRoll\tName\tMarks\n");
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
printf("\n===================================");
while(fread(&Stu,sizeof(Stu),1,fp)>0)
{
printf("\n\t%d\t%s\t%.2f",Stu.roll,Stu.name,Stu.marks);
}
printf("\n===================================");
fclose(fp);
}
void printPassStudent()
{
FILE *fp;
struct Student Stu;
fp = fopen("StudentRec.dat","r");
printf("\n===================================");
fclose(fp);
void printSpecificRec()
{
FILE *fp;
int n;
struct Student Stu;
fp=fopen("Studentr.dat","rb");
if (fp==NULL)
{
printf("\n error in opening file");
exit(1);
}
printf("\nEnter the record no to be read =>");
scanf("%d",&n);
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
fseek(fp,(n-1)*sizeof(Stu),0);
fread(&Stu,sizeof(Stu),1,fp);
printf("\nRoll no = %d\nName = %s\nMarks =
%.2f",Stu.roll,Stu.name,Stu.marks);
fclose(fp);
void main()
{
char op;
clrscr();
writeRecord();
do
{
printf("\nPress a for print all the Students records");
printf("\nPress p for print only pass Students records");
printf("\nPress s for print only specific position record");
printf("\nPress e for exit =>");
fflush(stdin);
scanf("%c",&op);
switch(op)
{
case 'a':
printRecord();
break;
case 'p':
printPassStudent();
break;
case 's':
printSpecificRec();
break;
case 'e':
exit(0);
default:
printf("\nWrong opt");
}
getch();
clrscr();
}while(op!='e');
getch();
}
Output#
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
Records
Roll Name Marks
===================================
1 Ram 28.00
2 Mayur 55.00
3 Vedika 78.00
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
4 Mansi 39.00
5 Manav 65.00
===================================
===================================
2 Mayur 55.00
3 Vedika 78.00
5 Manav 65.00
===================================
Roll no = 3
Name = Vedika
Marks = 78.00
4.5.4 ftell()
ftell() in C is used to find out the position of file pointer in the file with respect to
starting of the file.
Sytnax# Example#
long ftell(FILE *pointer) int position;
FILE *f1;
f1=fopen("abc.txt","rb");
position=ftell(f1);
Example# Consider above Student file which contains three records and find
total no of records and total no of bytes.
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
#include <stdio.h>
#include<conio.h>
struct Student
{
int roll;
char name[25];
float marks;
};
main () {
FILE *fp;
int len;
struct Student s1;
int totalrec;
clrscr();
fp = fopen("StudentR.dat", "r");
len = ftell(fp);
totalrec=len/sizeof(s1);
fclose(fp);
getch();
}
Output#
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
4.6 Command Line Arguments
It's the arguments supplied to main() program when the program is invoked. In common
case this parameter or argument is a name of the file which main function should
process.
Program execution always start with main() function. main() function can have
arguments. After successful compilation and linking of the object file, compiler generates
the executable file.
These arguments are passed with executable file. They are known as command line
arguments because they are passed at the time of executing the program.
Example#
If the executable file name is test.exe than in command line we can pass the arguments
as:
argc argument will stores the value 4 because there are three arguments passed
including file name itself.
argv[0] will stores test, argv[1] will stores Prem, argv[2] will stores Ratan, argv[3] will
stores Dhan.
How To Run?
1. Press f9 key
2. Exe file is created for our program in TC\Bin (Check)
3. Clear the Run -> Arguments -> Clear it
4. File -> Dos Shell -> Go where your TC\Bin (Check)
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
#include<conio.h>
#include<stdio.h>
Output#
How to run? Press f9 then Go to Dos prompt and …..
#include<conio.h>
#include<stdio.h>
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
for(i=0;i<argc;i++)
{
printf("\n\nArgv[%d]=%s",i,argv[i]);
}
getch();
Output#
#include<conio.h>
#include<stdio.h>
while(ch!=EOF)
{
ch=getc(read);
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
printf("%c",ch);
}
}
else
{
printf("\nInvalid arguments");
}
getch();
}
Output#
#include<conio.h>
#include<stdio.h>
while(ch!=EOF)
{
ch=getc(f1);
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
putc(ch,afile);
}
fclose(f1);
f2=fopen(argv[2],"r");
while(ch1!=EOF)
{
ch1=getc(f2);
putc(ch1,afile);
}
fclose(f2);
fclose(afile);
}
else
{
printf("\invalid arguments");
}
getch();
}
Output#
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
www.shyamsir.com 78 74 39 11 91
Dr. Shyam N. Chawda, C Language Tutorial , 78 74 39 11 91
www.shyamsir.com 78 74 39 11 91