Unit 10 File Handling in C
Unit 10 File Handling in C
Hrs)
1
Contents of the unit
• Concept of File, Opening and closing of File, Input Output Operations
in File, Random access in File, Error Handling in Files
2
Introduction
• The input output functions like printf(), scanf(), getchar(), putchar(), gets() are
known as console oriented I/O functions which always use keyword for input
device and computer screen for output device
• Using these library functions, the entire data is lost when either the program
is terminated or the computer is turned off.
4
Introduction
• A file is a place on the disk where a group of related data is stored.
• The data file always allows us to store information permanently and
to access later that information whenever necessary.
• Programming language C has various library functions for creating and
processing data files.
5
Disk File I/O
• For each, binary and text files, there are a number of formatted and
unformatted library functions in C.
• There are two types of file I/O.
1. Standard I/O (High Level I/O)
2. System I/O (Low level I/O)
Standard I/O is the most common way of performing I/O in C programs.
System I/O provides fewer ways to handle data than Standard I/O and it
can be considered a more primitive system and it employs the techniques
much like those used by operating system
6
Disk File I/O
• Standard I/O provides four different ways of reading and writing data
where as system I/O, in contrast uses record I/O as only one type of
reading /writing data.
• When data is read or written one character at a time it is called
character I/O (fgetc(), fputc())
• When data is read or written as strings using functions fgets() and
fputs(), it is called string I/O.
• When data is read or written into disk in a format analogous to that
generated by scanf() and printf() functions as a collection of values
that may be mixed types, we call it formatted I/O. for this we have
fscanf() and fprintf() functions.
7
Opening and Closing a File
• A program must open a file before reading and writing operation on
the file.
• Opening a file establishes a link between the program and the
operating system.
• This provides the operating system the name of the file and the mode
in which the file is to be opened.
• While working with high level data file, we need buffer area
(temporary memory) where the information is stored temporarily in
the course of transferring data between computer memory and data
file.
8
Opening and Closing a File
• The buffer is established as
• FILE * ptr_variable
• This associates a file name with the buffer area and specifies how the data
file will be utilized (File opening mode).
• The function fopen() returns a pointer to the beginning of the buffer area
associated with the file.
• A NULL value is returned of the file can not be opened due to some reasons
10
Opening and Closing a File
• After opening a file , you can process data files as requirement.
• The closing of file ensures that all outstanding information associated with the file is
flushed out from the buffers and all links to the file are broken.
• It searches specified file. If the specified file exists, it loads the file into
memory and sets up a pointer which points to the first character
within it.
13
File Opening Mode
• Write Mode(“w”): The “w” mode opens a file for writing purpose.
• It searches specified file. If the specified file already exist, the content
within the file are overwritten.
15
File Opening Mode
• Read and Write(“r+”) Mode: It opens file both reading and writing
purpose.
• It searches the specifies file. If the specified file exists, the program
loads the file into memory and set up a pointer which points to the
first character in it.
• Again, it returns NULL if the file does not exists.
• After reading the content of the file, we can write some content on
the file.
• Thus, the possible operations are : reading existing contents, writing
new contents, modifying existing contents of the file.
16
File Opening Mode
• Write and Read (“w+”) Mode: It opens file for reading and writing
purpose.
• If the specified file exists, its contents are destroyed. If the file does
not exists, the new file is created.
• It returns the NULL character if it is unable to open the file.
• The possible operations are: “writing new contents, reading them
back and modifying existing contents of the file”.
• Note: If the file does not exist, new file is created in “w+” but not in
“r+”
17
File Opening Mode
• Append and Read (“a+) Mode: This mode opens an existing file for
reading and appending purpose.
• A new file is created if the specified file does not exist,
• The possible operations are “reading existing contents, appending
new contents to the end of file but it can not modify existing content”.
18
Library Functions for Reading from
and/Writing to a File
• String Input/Output:
• Using string I/O functions, data can be read from a file or written to a
file in the form of array of characters.
• fgets(): It is used to read string from file.
• Syntax: fgets (string_variable, int_value,file_ptr_variable);
• Here, int_value denotes the number of characters in a string.
• The function reads a string from a file representing file_ptr_variable
and stores in a variable string_variable.
•
19
Library Functions for Reading from
and/Writing to a File
• fputs(): It is used to write a string to a file.
• Syntax:
• fputs(string, file_ptr_variable);
• Here, the string_variable is written to a file representing
file_ptr_variable.
20
Example 1
• Write a program to write a message “welcome to Nepal” to file named “welcome”
• #include<stdio.h>
• #include<conio.h>
• int main()
• {
• FILE *fptr;
• fptr = fopen("welcome.txt","w");
• if(fptr==NULL)
• {
• printf("File can not be opened");
• }
• else
• {
• printf("File created Successfully");
• }
• fputs("Welcome to Nepal",fptr);
• fclose(fptr);
• return 0;
• } 21
Example 2
• Write a C program that reads the content of the file “welcome.txt” and display the message on monitor
• #include<stdio.h>
• #include<conio.h>
• int main()
• {
• FILE *fptr;
• char str[100];
• fptr = fopen("welcome.txt","r");
• if(fptr==NULL)
• {
• printf("File can not be opened\n");
• }
• else
• {
• printf("File opened Successfully\n");
• }
• fgets(str,100,fptr);
• printf("Content of file:\n%s",str);
• fclose(fptr);
• return 0;
• }
22
Output
23
Character Input/Output
• Using character I/O functions, data can be read from a file or written
to a file one character at a time.
• For this we have two functions.
1. fgetc(): It is used to read a character at a time from a file. Its syntax
is: char ch = fgetc(file_pointer);
2. fputc(): This function is used to write character to file. Its synyax is:
fputc(char ch, file_pointer);
24
Example
• Write a program to write some text to file using fpuct() functions.
• #include<stdio.h>
• int main()
• {
• FILE * fp;
• char ch;
• fp = fopen("C:\\janak\\myfile","w");
• if(fp==NULL)
• printf("The file is not created\n");
• else
• {
• printf("Enter some text and enter at the end\n");
• while((ch=getchar())!='\n')
• {
• fputc(ch,fp);
• }
• }
• fclose(fp);
• return 0;
• }
25
• Write a program to read content of previous file.use fgetc() function
• #include<stdio.h>
• int main()
• {
• FILE * fp;
• char ch;
• fp = fopen("C:\\janak\\myfile","r");
• if(fp==NULL)
• printf("The file is not opened\n");
• else
• {
• while((ch=getc(fp))!=EOF)
• {
• putchar(ch);
• }
• }
• fclose(fp);
• return 0;
• }
26
• Write a C program that appends contents to the end of given file
• #include<stdio.h>
• int main()
• {
• FILE * fp;
• char ch;
• fp = fopen("C:\\janak\\myfile","a");
• if(fp==NULL)
• printf("The file is not opened\n");
• else
• {
• printf("Enter some text to append and enter at the end\n");
• while((ch=getchar())!='\n')
• {
• fputc(ch,fp);
• }
• }
• fclose(fp);
• return 0;
• }
27
• Write a C program that copies contents one file to another file using character I/O.
• #include<stdio.h>
• int main()
• {
• FILE * fp1,*fp2;
• char ch;
• fp1 = fopen("C:\\janak\\myfile","r");
• fp2 = fopen("C:\\janak\\myfile1","w");
• if(fp1==NULL)
• printf("The file is not opened\n");
• else
• {
•
• while((ch=getc(fp1))!=EOF)
• {
• putc(ch,fp2);
• }
• }
• fclose(fp1);
• fclose(fp2);
• return 0;
• }
28
Formatted Input/Output
There are two functions for formatted input and output in file handling
namely fprintf() and fscanf().
These functions are used to read numbers or strings from a file or to
write to a file in a format as our requirement.
fprintf() : It is formatted output function which is used to write integer,
char, or string data to a file.
syntax: fprintf(file_pointer, “control string”, list of variables);
fscanf() : It is formatted input function which is used to read integer,
char or string data from a file.
syntax: fscanff(file_pointer, “control string”, list of variables);
29
• // write a C program to writes records to file • FILE *fp;
• #include<stdio.h> • struct student s;
• struct student • fp = fopen("C:\\janak\\std.txt","a");
• { • if(fp==NULL)
• int rollno; • {
• char name[20]; • printf("File is not created\n");
• int marks; • }
• }; • else
• void read(struct student *s) • {
• { • printf("File created\n");
• printf("Enter roll no, name and marks • read(&s);
of a stduents\n"); • fprintf(fp,"%d\t%s\t%d\
• scanf("%d%s%d",&s->rollno,s- n",s.rollno,s.name,s.marks);
>name,&s->marks); • }
• } • fclose(fp);
• int main() • }
30
• {
• // write a C program to reads records to file • struct student s;
• #include<stdio.h> • fp = fopen("C:\\janak\\std.txt","r");
• struct student • if(fp==NULL)
• { • {
• int rollno; • printf("File is not created\n");
• char name[20];
• int marks; • }
• }; • else
• void display(struct student s) • {
• { • printf("File created\n");
• printf("%d\t%s\t%d\ • while((fscanf(fp,"%d%s
n",s.rollno,s.name,s.marks); %d",&s.rollno,s.name,&s.marks))!=EOF)
• } • display(s);
• int main() • }
• { • fclose(fp);
• FILE *fp; • }
31
End Of File (EOF)
• The constant EOF represents an integer and determines whether the
file associated with a file pointer has reached end of file or not.
• This pointer is sent to the program by the operating system and is
defined in the header file stdio.h.
• While creating a file, the operating system transmits the EOF signal
when it finds the last character to the file.
• In text mode, a special character 1A hex (26 decimal) is inserted after
the last character in the file.
• An attempt to read content after EOF might either cause the program
to terminate with an error or result in an infinite loop situation.
• The last point of file is detected using EOF while reading the file.
32
Binary Data Files
• The binary files organize data into blocks containing contiguous bytes
of information.
• A binary file is a file of any length that holds byte with values in the
range 0 to 255.
• The binary files are recognized as a stream of bytes and programming
languages tend to work with streams rather than files.
• In binary files, the opening mode of text mode file is appended by a
character ‘b’.
33
Binary Data Files
1. “r” is replaced by “rb”.
2. “w” is replaced by “wb”.
3. “a” is replaced by “ab”.
4. “r+” is replaced by “r + b”.
5. “w+” is replaced by “w + b”.
6. “a+” is replaced by “a + b”.
34
• Write a C program to write a text “ This is my file” to a data file in binary mode. Also its content and print on monitor.
• #include<stdio.h>
• #include<conio.h>
• #include<stdlib.h>
• int main()
• {
• FILE * fp;
• char ch;
• fp = fopen("C:\\janak\\text.txt","w+b");
• if(fp == NULL)
• {
• printf("File is not created\n");
• exit(0);
• }
• fputs("Welcome to Nepal",fp);
• rewind(fp);
• printf("Content of file\n");
• while((ch=fgetc(fp))!=EOF)
• {
• printf("%c",ch);
• }
• fclose(fp);
• getch();
• return 0;
35
• }
Difference between Binary Mode
and Text Mode
1. In text mode, a special character EOF is inserted after the last
character in the file to mark the end of file. But there is no such
special character present in the binary mode. The binary mode files
keeps track of the end of file from the number of characters
presented in the directory entry of the file.
2. In text modem the numbers are stored as string of characters
whereas in binary format they are stored in the same way as they
are stored in computer’s main memory. For example the number
12 occupies four bytes primary memory but it occupies 2 bytes of
disk in the text mode.
36
Record Input/Output
• It is clear that character I/O and string I/O permits reading and writing of
characters data only, whereas the formatted I/O) permits reading and
writing of characters data as well as numeric data.
• However, the numbers are stored as sequence of characters, not the way
they are stored in memory.
• As a result, they take a lot of disk space.
• In addition to that, these methods provide no direct way to read and
write complex data types such as array and structures.
• Through , the arrays and structures can be handled by reading and writing
each array element one at a time, but this approach is very inefficient.
37
Record Input/Output
• The solution to these problems are records I/O also known as block I/O.
Thus, the arrays, structures, array of structures etc can be read from a file
or written to a file as a single unit using record I/O.
The functions fwrite() and fread() are used for record read and write
respectively.
38
Record Input/Output
• The syntax for fread() is as:
• fread(&var, sizeof(data type),no_of _data, fptr);
39
• // Write a C program to write structure to file • if(fp == NULL)
• #include<stdio.h> • {
• #include<string.h> • printf("File can not be opened\n");
• struct student • }
• { • else
• int rn; • {
• char name[20]; • fwrite(&s,sizeof(s),1,fp);
• int marks[10]; • }
• }; •
• int main() • return 0;
• { • }
• FILE *fp; •
• struct student s = {1,"Kamal",200}; •
• fp = fopen("C:\\janak\\std.txt","wb");
40
• // Write a C program to read structure • if(fp == NULL)
form //file • {
• #include<stdio.h> • printf("File can not be opened\
• #include<string.h> n");
• struct student • }
• { • else
• int rn; • {
• char name[20]; • fread(&s,sizeof(s),1,fp);
• int marks; • printf("Name:%s\n",s.name);
• }; • printf("Rollno:%d\n",s.rn);
• int main() • printf("Marks: %d\n",s.marks);
• { • }
• FILE *fp; • return 0;
• struct student s; • }
• •
• fp = fopen("C:\\janak\\std.txt","rb"); •
41
Direct /Random Access
• The reading and writing operations in all examples discussed so are
sequential.
• While reading data from a file, the data items are read from the
beginning of the file in sequence until end of the file.
• Similarly, while writing data to a file, data items are placed one after
the other in a sequence.
• But, sometimes, we have to access a particular data item placed in
any order without starting from the beginning.
• Such type of access to a data item is called direct or random access
42
Direct /Random Access
• fseek() function: It sets file pointer associated with file to a new
position.
• This function is used to move the file pointer to different location.
• Syntax:
• fseek (fptr, offset, mode)
• where, fptr is a file pointer, offset is an integer that specifies the
number of bytes by which file pointer is moved and mode specifies
from which position the offset is measured.
• The value of mode may be 0,1 or 2.
43
Direct /Random Access
• fseek (fptr, 0, SEEK_SET) : Moves file pointer at beginning of the file
• fseek (fptr, 0, SEEK_END): Moves file pointer at the end of the file
• fseek (fptr, 10, SEEK_SET): Moves the file pointer at 10 bytes right
from the beginning of file
• fseek(fptr, -2, SEEK_CUR): Moves the file pointer 2 bytes ;eft from the
current position
44
Direct /Random Access
• rewind() function : One way of positioning the file pointer to the
beginning of the file is to chose the file and then reopen it again.
• The same task can be accomplished using rewind() function.
• This function positions the file pointer in the beginning of the file.
• The use of function rewind() is equivalent of using fseek(fptr,
0,SEEK_SET)
45
Direct /Random Access
• ftell() function :This function determines the current location of the
file pointer within the file .
• It returns integer value.
• syntax: ftell (fptr);
• where
• fptr is a file pointer for the currently opened file.
46
• //Write a C program that searches n",s.rn,s.name,s.marks);
student record in a file • }
• #include<stdio.h> • int main()
• #include<conio.h> • {
• #include<string.h> • FILE *fp;
• struct student • struct student s,r;
• { • int n=2,i,found=0;
• int rn; • char name[20];
• char name[20]; • fp = fopen("C:\\janak\\
• int marks; std.txt","rb");
• }; • printf("Enter name of students to
• void display(struct student s) be seaeched\n");
• { • scanf("%s",name);
• printf("%d\t%s\t%d\ •
47
• if(fp == NULL) •
• { • }
• printf("File can not be opened\ • if(found==1)
n"); • {
• } • printf("Record found\n");
• else • printf("Roll no\tname\tMarks\n");
• { • display(s);
• • }
• while((fread(&s,sizeof(s),1,fp))) • else
• { • printf("Record not found");
• if(strcmp(name,s.name)==0) • return 0;
• { • }
• found = 1; •
• break; •
• }
• }
48
• // Delete records of students whose name starts with 'R' from "C:\\janak\\students.txt"
• #include<stdio.h>
• #include<conio.h>
• #include<stdlib.h>
• #include<string.h>
• struct student
• {
• int rollno;
• char name[20];
• int marks;
• };
• void display(struct student s)
• {
• printf("%d\t%s\t%d\n",s.rollno,s.name,s.marks);
• }
• char lastchar(char name[])
• {
• char ch = name[strlen(name)-1];
• return ch;
• }
49
• int main()
•{
• FILE *fp,*fp1;
• struct student s,temp;
• int r,count=0,found=0;
• char choice[10];
• fp = fopen("C:\\janak\\student.txt","r");
• fp1 = fopen("C:\\janak\\std.txt","w");
• if(fp==NULL)
• {
• printf("File not created\n");
• }
•
50
• else
• {
• printf("File opended\n");
• while(fread(&s,sizeof(s),1,fp))
• display(s);
• printf("Do you want to delete(yes/no)\n");
• scanf("%s",choice);
• if(strcmp(choice,"no")==0)
• exit(0);
• printf("Enter rollno of student whose record is be be deleted\
n");
• scanf("%d",&r);
• rewind(fp);
• 51
• while(fread(&s,sizeof(s),1,fp))
• {
•
• if(s.rollno==r)
• {
• found=1;
• }
• else
• {
• fwrite(&s,sizeof(s),1,fp1);
• }
•
• }
•
• }
• fclose(fp);
• fclose(fp1);
• remove("C:\\janak\\student.txt");
• rename("C:\\janak\\std.txt","C:\\janak\\student.txt");
• remove("C:\\janak\\std.txt");
• if(found==0)
• printf("Record not found\n");
52
• }
• Write a C program that writes student records to file • fp = fopen("C:\\janak\\student.txt","a");
• #include<stdio.h> • if(fp==NULL)
• #include<conio.h> • {
• #include<stdlib.h> • printf("File not created\n");
• struct student • }
• { • else
• int rollno; • {
• char name[20]; • printf("File opened\n");
• int marks; • for(int i=1;i<=3;i++)
• }; • {
• void read(struct student *s) • read(&s);
• { • if(fwrite(&s,sizeof(s),1,fp)==1);
• printf("Enter rolno,name and marks of student\ • }
n"); • printf("Record written to file");
• scanf("%d%s%d",&s->rollno,s->name,&s->marks); • }
• } • fclose(fp);
• int main() • getch();
• { • return 0;
• FILE *fp; • }
• struct student s;
53
• Write a C program that deletes student records from file
• #include<stdio.h>
• #include<conio.h>
• #include<stdlib.h>
• #include<string.h>
• struct student
• {
• int rollno;
• char name[20];
• int marks;
• };
• void display(struct student s)
• {
• printf("%d\t%s\t%d\n",s.rollno,s.name,s.marks);
• }
54
• int main()
• {
• FILE *fp,*fp1;
• struct student s,temp;
• int r,count=0,found=0;
• char choice[10];
• fp = fopen("C:\\janak\\student.txt","r+");
• if(fp==NULL)
• {
• printf("File not created\n");
• }
• else
• {
• printf("File opended\n");
• while(fread(&s,sizeof(struct student),1,fp))
• display(s);
• printf("Do you want to update(yes/no)\n");
• scanf("%s",choice);
• if(strcmp(choice,"no")==0)
• exit(0);
• printf("Enter rollno of student whose record is be be updated\n");
• scanf("%d",&r);
• rewind(fp);
• 55
• while(fread(&s,sizeof(s),1,fp))
• {
• if(s.rollno==r)
• {
• printf("Record found\n");
• printf("Enter rolno, name and marks of student\n");
• scanf("%d%s%d",&temp.rollno,temp.name,&temp.marks);
• fseek(fp,sizeof(temp)*count,0);
• if(fwrite(&temp,sizeof(temp),1,fp)==1)
• printf("Record updated successfully\n");
• found=1;
• break;
• }
• count = count+1;
• }
• }
• if(found==0)
• printf("Record not found\n");
• } 56
Errors in File Handling
• Error: Error is an illegal operation performed by the user which results
in abnormal working of the program.
• It is quite common that an error may occur while reading data from
file or writing data to a file.
57
Types of Errors occurring in file
1. When trying to read a file beyond EOF indicator
2. When trying to read a file that does not exist
3. When trying to use a file that has not been opened.
4. When trying to access a file that is in an appropriate mode.
5. When writing to a file that is opened for read only
58
Types of Errors occurring in file
• C language does not provide any direct support for error handling.
• However Library Functions is used to check Errors in the File Stream is
defined in <error.h> header file.
59
Types of Errors occurring in file
• ferror(): The ferror() function is used to check any errors in the file
stream.
• syntax:
• int ferror(“FILE *stream);
• Example:
• if (ferror ( fp ))
• { printf(“Error Message”);
• }
• If errors occurs the ferror () returns non-zero value otherwise returns
zero(0) value
60
The feof () function
• The C library function int feof(FILE *stream) tests the end-of-file indicator for the
given stream.
• In C language when we are using a stream that links with a file, then how can we
determine we come to the end of a file.
• To solve the problem we have to compare an integer value to the EOF value.
Through the feof() function we determine whether EOF of a file has occurred or
not.
• The prototype of this function is :
• int feof(FILE* filename);
• It returns the value zero when end of the file has not occurred, otherwise it
returns 1.
61
• #include <stdio.h> • if(feof(fp))
• #include <stdlib.h> • {
• int main() • break;
• { • }
• FILE* fp; • fgets(str, 100, fp);
• char str[100]; • printf("%s", str);
• fp = fopen("C:\\Users\\Dell\\Documents\\ • }
eoffile.cpp", "r"); • fclose(fp);
• if(fp==NULL) { • return 0;
• printf("Cannot open the file..."); • }
• exit(1);
• }
• printf("File content is--\n");
• while (1)
• {
62
63
Example ferror() function
• #include<stdio.h>
• int main()
• {
• FILE *fp;
• char c;
• fp = fopen ("C:\\janak\\file.txt",“w");
• c = fgetc(fp);
• if(ferror(fp))
• {
• printf("Error in reading from file : file.txt\n");
• }
• fclose (fp);
• return(0);
64
• }