Session 07
File Handling in C
1
Session Objectives • To know how to create and handle files. • To be able to differentiate between various types of files. • To be in a position to write involved programs like inventory control, record handling in files etc.,
2
Session Topics • • • •
File the structured data type Temporary and permanent file Organization of file File operation
3
Files • Files are helpful in providing permanent storage of input/output that can be accessed at any point of time later. • A file is a region of memory space in the storage media and it can be accessed using the library functions available in stdio.h or by the system calls of the operating system. • File contains bytes of information. • NOTE:It is not a data type. 4
Classification of Files High Level Files
Low Level Files
• The files which are accessed by using library functions are known as High Level Files. • These files are portable as they make use of library functions common to all operating systems. • Stream oriented files.
• The files which are accessed by using system calls of the operating system are known as Low Level Files. • These files make use of the system calls of the operating system under which the program is run. • System oriented files.
5
Streams A stream is a source of data or destination of data that may be associated with a disk or other I/O devices. The source stream provides data to a program and it is known as an input stream. The destination stream receives the output from the program and is known as output stream. A stream is a pointer to a buffer of memory which is used for transferring the data.
6
Types of I/O Streams Text Stream
It is a sequence of lines of text. A file created using a text stream is called as a Text File.
Binary Stream
It is a sequence of unprocessed bytes. A file created using a binary stream is called as a Binary File.
7
FILE & File Pointer FILE is a structure defined in stdio.h and also it is predefined data type using typedef. The pointer to a FILE data type is called as a File Pointer. A file pointer points to the block of information of the stream that has just been opened.
8
Why File Handling? It is a very difficult to input large volume of data through terminals and apart from this, it is time consuming to enter such large volume of data using keyboard. If the program is terminated for any of the reason or computer is turned off, the entire input data is lost.
9
File Operations The various file operations that are performed are: Open a file Read data from the file Write data into the file Closing a file
10
File Operating Modes Mode
Meaning
Description
R
read only
File pointer is set to beginning if file
W
write only
1. 2.
If the file already exists, the contents are lost. If file does not exist, a file is created for writing.
A
append
1.
If the file already exists, file pointer is set to end of file in write mode. If the file does not exists, it is created for writing and file pointer is at the beginning.
2.
r+
read write
Opening for read and write and the file pointer points to the beginning of file.
w+
read write
1. 2.
a+
append
1. 2.
Opened for read and write and the file contents are lost if file exists. If file does not exist, the file is read write and file pointer points to beginning of file. Opened for read, write and append File pointer is at the end of file
11
fopen() The file should be opened before reading a file or before writing into a file. Syntax: fp = fopen(char *filename,char *mode) where - fp is a file pointer of type FILE - filename holds the name of the file to be opened.The filename should be a valid identifier. - mode details Return Values: - file pointer if successful - NULL if unsuccessful
Example: FILE *fp1,*fp2; fp1=fopen(file_1,”r”); fp2=fopen(file_2,”w”) 12
fclose() • •
This function is used to close the opened file. A file should be closed when all file operations are over. This ensures that all buffers are flushed and all the links to the file are broken. Syntax: int fclose(FILE *fp) fp is a file pointer Return Values: -
0 if successful EOF on error Example: fclose(fp1); fclose(fp2); 13
File Handling:An Example #include<stdio.h> #define NULL 0 void main() { FILE *fp; fp = fopen(“sample.dat”,”r+”); if(fp = NULL) printf(“\n Error!Cannot open the file”); else { ……………..; fclose(fp); } }
14
fscanf() Syntax: fscanf(fp,”control string”,list); - fp is a file pointer - the variables specified in the list will take values from the file specifed by fp using the specifications provided in control string. Example: fscanf(fp,”%d %s %f”,&id,name,&salary); This function returns the number of items that are successfully read from the file identified by file pointer fp. 15
fprintf() Syntax: fprintf(fp,”Control string”,list); - fp is a file pointer - the values of the variables specified in the list will be written into the file identified by fp using the specifications provided in control string. Example: fprintf(fp,”%d %s %f”,id,name,salary); This function returns the number of items that are successfully written into the file identified by file pointer fp. 16
Error Handling During I/O operations, the following errors may occur 2. Reading beyond end of file marker 3. Unable to open a file 4. Invalid file name 5. Attempting to write to a write-protected file
feof() -
This function is used to check for end of file. This function accepts the file pointer as a parameter. Return values: If end of file is detected, a non zero value is returned. If end of file is not detected, zero is returned. Example: If fp points to EOF if(feof(fp)) printf(“End of file is reached\n”); 17
ferror() This macro is used to get the status of file. This function accepts the file pointer as a parameter. Return values: - If error is detected, a non zero value is returned. - If error is not detected, zero is returned. Example: If fp is a file pointer if(ferror(fp)!= 0) printf(“Error in the file \n”);
18
Program which provides error handling in files void main(){ FILE *fp; int i; char file_name[10]; char ch; printf(“Enter the file name\n”); scanf(“%s”,file_name); fp = fopen(file_name,”r”); if(fp == NULL){ printf(“Not successful\n”); exit(0);} for(i=0;i<30;i++){ if(feof(fp)){ printf(“Very few characters present in file\n”); exit(0);} ch = getc(fp); printf(“%c”,ch);} }
19
File Control Functions ftell() This function is used to obtain the current position of the file pointer. Syntax: long ftell(FILE *fp); Return Values: - Returns the current position of the file pointer, on success - Returns EOF on error. Example: If this function returns 1000, it indicates 999 characters have been read so far from the file and the file pointer fp is pointing to the 1000th character in the file.
20
fseek() This function is used to reposition the file pointer i.e, it is used to move the file pointer to the desired position within the file. Syntax: int fseek(FILE *fp,long offset, int start_point); - fp is a file pointer - offset can take positive,negative or zero value and specify the number of bytes to be moved from the location specified by start_point. - start_point an take one of the values. 0 indicates beginning of file. 1 indicates from the current position. 2 indicates from the end of file. Return Values: If success, returns 0. Unsuccessful, returns non zero value. Example: fseek(fp,0,0 ) file pointer moves to the beginning of file 21
rewind() This function accepts file pointer as a parameter and resets the position of the file pointer to the start of the file. Syntax: rewind(file pointer); Example: If file pointer fp is in position 1000, by executing this function, the file pointer fp is set to the very first position in the file.
22
Summary • Files are helpful in providing permanent storage of input/output that can be accessed at any point of time later. A stream is a source of data or destination of data that may be associated with a disk or other I/O devices. FILE is a structure defined in stdio.h and also it is predefined data type using typedef. The pointer to a FILE data type is called as a File Pointer. A file pointer points to the block of information of the stream that has just been opened.
23
Thank You!
24