files imp notes
DESCRIPTION
it gives a complete understanding of all functions with examplesTRANSCRIPT
FILE HANDLING IN C
INTRODUCTION
Computer stores programs and data in secondary memory in the form of files. Storing programs and data in primary memory is not preferred due to its volatility nature which loses its contents when the power goes off.
Interaction between program console and file
File
It is collection of related data stored on secondary storage devices like disk.
Files represent programs and data. Data may be numeric, alphabetic or alphanumeric.
A file is named and is referred to by its name.
It is collection of bits, bytes, lines or records.
Types of Files
Text Files
Binary Files
Secondary memory Data files
Primary memory
Programs+Data
Keyboard o/p screen
get data from Write data
Write data Read data Program-file
Program-console
Text Files
They are the files that contains letters, digits and symbols. These Files contains the characters coded from ASCII Character set.
Binary Files
It is sequential access file in which data are stored and read back one after the another in binary format instead of ASCII format.
Operations on Files
The common operations that can be performed on files are
Naming File
Opening and Closing of files
Reading and Writing of Files
Naming of File
The file name must be specified for particular file. The file name is string of characters. The valid file names are
File1.txt, File2.c, File3.h, File4.dat and so on.
If the file is used for storing text .txt extension is used. If the file stores C program .c extension is used. If the file is header file .h extension is used.
Opening and Closing of Files
fopen()
The function fopen() is used for opening file. Every File that is opened returns a pointer to particular file. The syntax is given below
fptr=fopen(“filename or path of file”,mode);
filename or path of file is the name of file being opened. If path of file is not mentioned file exists in current directory.
Eg: If you are working in C:\Tc and if the path of file is not mentioned then file exists in C:\Tc directory.
Mode of opening can be any one of following:
Text Files
r Opens File for reading only.
w Opens File for writing only.
a Opens File for appending only.
r+ Opens File for reading and writing.
w+ Opens File for reading and writing.
a+ Appends file for read/write
Binary Files
rb Opens File for reading only.
wb Opens File for writing only.
ab Opens File for appending only.
rb+ Opens File for reading and writing.
wb+ Opens File for reading and writing.
ab+ Appends file for read/write
‘fptr’ is pointer variable that contains the address of structure FILE that has been defined in stdio.h header file.
Eg
FILE *fptr;
fptr=fopen(“text.txt”,”r”);
the text.txt file is opened for reading only.
fclose()
fclose() is used for closing file which is being opened. The syntax is
fclose(fptr);
Eg:
FILE *fptr;
Fptr=fopen(“text.txt”,”r”);
/* perform operations on file */
fclose(fp);
FILE I/O FUNCTIONS(READING AND WRITING OF FILES)
Two Categories of File I/O functions
1. Unformatted ( No format for I/O)
2. Formatted
Unformatted File I/O functions
Character oriented File I/O functions( fgetc() and fputc())
String oriented File I/O functions(fgets() and fputs())
Formatted File I/O functions
fprintf() and fscanf()
Character Oriented File I/O functions
fgetc()
It is used to read character from file. Syntax is given below
ch=fgetc(fptr);
ch is character variable and fptr is pointer to FILE. This function reads the character from file and returns character value which is collected by variable ‘ch’
Example explanation of fgetc()
Step 1: opens File in read mode which is already been created.
Step2: Read individual character from the file till end of file is reached.
Step 3: Close the file.
Creating File say ‘file1.txt’.
Left click ->new->text document
Write data to file if data does not exist manually or using program
Program
#include<stdio.h>#include<conio.h>main(){ FILE *fp; char ch; clrscr(); fp=fopen("text.txt","r"); /* opens file for reading */ ch=fgetc(fp);/* read character from file and assign it to ch */ printf("%c",ch); /* Loop until the end of file is reached */ while(ch!=EOF) { ch=fgetc(fp); printf("%c",ch);
} fclose(fp);}
O/P
fputc()
It is used for writing character to file. The syntax is as follows
fputc(ch,fptr);
This function writes the contents of character ch to file represented by fptr.
Example Explanation for fputc()
Step 1: opens file in write mode which is already existed in current directory or create file which is not existing in current directory.
Step2: Write individual character one by one from program to the file.
Step3: Close the file.
Previous data in text.txt file without writing content
Program
#include<stdio.h>#include<conio.h>main(){ FILE *fp; char ch; clrscr(); fp=fopen("text.txt","w"); /* opens file for writing */ /* when the file is opened in write mode in already existing file the data in previous file will be overwritten with new data */ ch=getchar();/* read character from keyboard inorder to write data to file*/ /* Loop until the end of file is reached */ while(ch!=EOF) { fputc(ch,fp); ch=getchar(); } fclose(fp);}
Input from keyboard to write data to file
After writing content to file contents of text.txt file are overwritten with new data
Writing content to file which is not existing in current directory
Program
#include<stdio.h>#include<conio.h>main(){ FILE *fp; char ch; clrscr(); fp=fopen("text1.txt","w"); /* opens file for writing */ /* when the file is opened in write mode in already existing file the data in previous file will be overwritten with new data */ ch=getchar();/* read character from keyboard inorder to write data to file*/ /* Loop until the end of file is reached */ while(ch!=EOF) { fputc(ch,fp); ch=getchar(); } fclose(fp);}After compiling and running the above program new file text1.txt will be created.
The contents of text1.txt file are empty
Take input from keyboard to write data to file
Now the contents of text1.txt file are
Appending the data to file say text1.txt which is already existing in current directory and data in that file is not empty.
Program
#include<stdio.h>#include<conio.h>main(){ FILE *fp; char ch; clrscr(); fp=fopen("text1.txt","a"); /* opens file for appending data at end */ /* when the file is opened in append mode in already existing file the data will be added to the previous file at the end */ ch=getchar();/* read character from keyboard inorder to append data to file*/ /* Loop until the end of file is reached */ while(ch!=EOF) { fputc(ch,fp); ch=getchar(); } fclose(fp);}
Input from Keyboard
Contents of text1.txt file after appending are
String oriented I/O functions
fputs()
This function is used to write string to file. The syntax is given below
fputs(buffer,fptr);
buffer is the name of character array and fptr is pointer to FILE type. This function writes the string represented by buffer to file pointed to by fptr.
Example Explanation for fputs()
Step 1: Creates the file which is not existing in current directory or opens the file for writing string to file which is existing in current directory.
Step 2: Write the string to file.
Step 3: Close the file.
Program
#include<stdio.h>#include<conio.h>main(){ FILE *fp; char str[10]; int n,i; clrscr(); fp=fopen("text2.txt","w"); /* opens file for writing */ /* when the file is opened in write mode in already existing file the data in previous file will be overwritten with new data */ printf("enter number of students"); scanf("%d",&n); fflush(stdin);/* remove the previous data from input buffer */ /* loop through the number of students to enter names of students to write data to file */ for(i=1;i<=n;i++) { gets(str); fputs(str,fp); } fclose(fp);}
Input from keyboard to write String to text2.txt file
The contents of text2.txt file after writing string are
fgets()
This function is used to read string from file upto its specified size. The syntax of fgets() is given below
fgets(buffer,size,fptr);
buffer is name of character array,size is integer value, fptr is pointer to FILE type. This function reads string of maximum size-1 characters from file pointed to by fptr and copies data to the memory area denoted by buffer.
Example Explanation of fgets()
Step 1: Opens the file in read mode.
Step 2: Read the contents from file upto its maximum size.
Step 3: Close the file.
Program#include<stdio.h>#include<conio.h>main(){ FILE *fp; char str[10]; int size; clrscr(); fp=fopen("text2.txt","r"); /* opens file for reading string from file */ printf("enter size"); scanf("%d",&size); fgets(str,size,fp);/* reads string of size -1 characters from file pointed to by fp and store data in str */ puts(str);/* prints the string contents */ fclose(fp);}
O/P
Formatted I/O functions
fprintf()
This function is used to write data items which may be of different types to file. The syntax is given below
fprintf(fp,”control string”,argument-list);
fp is file pointer pointing to FILE type,control string specifies format specifiers and argument list contains the comma separated variables, values of which are to be written to the file.
Example Explanation of fprintf() function
Program#include<stdio.h>#include<conio.h>struct student{int rollno;char name[100];};main(){ struct student s; FILE *fp; int i,n; clrscr(); fp=fopen("text3.txt","w"); /* opens file for writing data types to file */ printf("enter number of student records"); scanf("%d",&n); for(i=1;i<=n;i++) { scanf("%d%s",&s.rollno,&s.name);/* scan student details */ fprintf(fp,"%d%s",s.rollno,s.name);/* write student data to file */ }
fclose(fp);}
Input from keyboard to write items of different types to file
The contents of text3.txt after writing are
fscanf()
This function is used to read multiple data items which may be of different types from file. The syntax is given below
fscanf(fptr,”control string”,arguments list);
fp is file pointer pointing to FILE type,control string specifies format specifiers and argument list contains the comma separated variables preceded by & symbol into which data read from file are to be copied.
Example Explantion of fscanf()
Program#include<stdio.h>#include<conio.h>struct student{int rollno;char name[100];};main(){ struct student s; FILE *fp; int i,n; clrscr(); fp=fopen("text3.txt","r"); /* opens file for reading data types from file */ while(!feof(fp)) /* loop through end of file is reached */ { fscanf(fp,"%d%s",&s.rollno,&s.name);/* scan student details from the file */ printf("%d%s",s.rollno,s.name);/* print student data */ } fclose(fp);}
O/P
Reading and Writing data to and from binary files
The main disadvantage of fprintf() is all data types are treated as characters for eg 234 occupies two bytes in memory but when data is stored in disk it occupies 3 bytes of memory. Thus large amount of data requires large space on disk. Hence storing data in text mode on disk turns out to be inefficient method.
To overcome this drawback the files should be read and written in binary mode. The functions used for reading and writing data in binary mode are
fread() fwrite()
fwrite() This function is used for writing structure block to file. The syntax is given below.
fwrite(&structure-variable,sizeof(structure),integer,fptr);
The first argument is address of structure to be written to disk, the second argument specifies size of structure in bytes, integer is number of records and fptr is pointer to file type.Example Explanation of fwrite()Program#include<stdio.h>#include<conio.h>struct student{int rollno;char name[100];};main()
{ struct student s; FILE *fp; int i,n; clrscr(); fp=fopen("text4.txt","wb"); /* opens binary file for writing structure of data*/ printf("enter the number of records"); scanf("%d",&n); for(i=1;i<=n;i++) { scanf("%d%s",&s.rollno,&s.name);/* scan student details */ fwrite(&s,sizeof(s),1,fp);/* write structure to file */ } fclose(fp);}Input from keyboard to write structure block to file
The contents of text4.txt are
fread() This function is used for reading structure block from file. The syntax is given below.
fread(&structure-variable,sizeof(structure),integer,fptr);
The first argument is address of structure to be read from disk, the second argument specifies size of structure in bytes, integer is number of records and fptr is pointer to file type.Example Explanation of fread()Program#include<stdio.h>#include<conio.h>struct student{int rollno;char name[100];};main(){ struct student s; FILE *fp; clrscr(); fp=fopen("text4.txt","rb"); /* opens binary file for reading structure block from file*/ while(fread(&s,sizeof(s),1,fp)) /* read strucure data from file till there is no content in file */ { printf("%d%s",s.rollno,s.name); }
fclose(fp);}O/P
Random Accessing of Files
The functions used for randomly accessing data from file are
fseek() ftell() rewind()
fseek() This function is used for setting pointer position in file at specified position. The syntax is given below
fseek(fp,displacement,pointer_position);
fp is pointer to FILE type. Displacement is positive or negative. This is number of bytes which are skipped backward(if negative) or forward(if positive) from current pointer position. Pointer_position can take one of 3 values 0,1,2. The meanings of values are given below.
Pointer_position Macro name Meaning0 SEEK_SET Beginning of file1 SEEK_CUR Current position of file2 SEEK_END End of file
Eg:fseek(fp,0,1)-Stay at the current positionfseek(fp,n,1)-move pointer forward by n bytesfseek(fp,-n,1)-go backward by n bytes from current position.
When operation is successful fseek returns zero.If an error occurs fseek returns -1.
ftell()
This function gives the value of current position pointer in file.
Syntaxftell(fp)
rewind()
This function is used for moving pointer to beginning of file
Example Explanation of functions(fseek(),ftell())
The contents of text1.txt file are
Program#include<stdio.h>#include<conio.h>main(){ FILE *fp; char ch; clrscr(); fp=fopen("text1.txt","r"); /* opens file for reading*/ fseek(fp,5,1); printf("File pointer position is %d",ftell(fp)); printf("\n");
while(!feof(fp)) { ch=fgetc(fp); printf("%c",ch);
} fclose(fp);}
O/P
Error Handling FunctionsThe situations under which I/O operations fail are
Trying to use file that has not been opened. Trying to open file which does not exist for reading purpose. Trying to open file for writing purpose when there is no disk space. Trying to write to read only file
The error handling functions are ferror() feof()
ferror()
This function takes file pointer as argument and returns non zero value if error is found such as writing data to file which is opened in read mode etc and zero otherwise.
Syntaxferror(fp)
feof()This function avoids reading file after the end of file mark.Syntaxfeof(fp)
Example Explanation
Trying to open file which doesnot exist in current directoryProgram#include<stdio.h>#include<conio.h>#include<stdlib.h>main(){ FILE *fp; char ch; clrscr(); fp=fopen("text5.txt","r"); if(fp==NULL) { printf("The file doesnot exist"); exit(1); } fclose(fp);}
Program
#include<stdio.h>#include<conio.h>#include<stdlib.h>main(){ FILE *fp,*fp1; char ch; clrscr(); fp=fopen("text1.txt","r"); if(fp==NULL) { printf("The file doesnot exist"); exit(1); } fclose(fp); fp1=fopen("text2.txt","r"); fputc('c',fp1); if(ferror(fp1)) { printf("The file is opened in read mode.it is not used for writing"); exit(1); } fclose(fp1);}O/P