Professional Documents
Culture Documents
Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two major problems : 1) It becomes cumbersome and time consuming to handle large volumes of data through terminals.
2) The entire data is lost when either the program is terminated or computer is turned off therefore it is necessary to have more flexible approach where data can be stored on the disks and read whenever necessary, without destroying the data. This method employs the concept of files to store data.
File is a place where data can be stored on the disks and read whenever necessary, without destroying the data. File basic operation: a) Naming a file b) Opening a file c) Reading data from a file d) Writing data to a file e) Closing a file
FILE *fp; fp=fopen(filename,mode); first line : The variable fp is a pointer to the data type FILE. second line: opens the file named file name and assigns an identifier to the FILE type pointer fp The file open function (fopen) serves two purposes: It makes the connection between the physical file and the stream. It creates a program file structure to store the information C needs to process the file.
FILE *p1, *p2; p1=fopen(data,r); p2=fopen(results,w); In case the results file already exists, its contents are deleted and the files are opened as a new file. If data file does not exist error will occur.
A file must first be opened properly before it can be accessed for reading or writing. When a file is opened, a stream is associated with the file. Successfully opening a file returns a pointer to (i.e., the address of) a file structure, which contains a file descriptor and a file control block.
Once the files are open, they stay open until you close them or end the program (which will close all files.)
fopen
R+ existing file is opened to the beginning for both reading and writing W+ same as w except both for reading and writing A+ same as a except for reading and writing
The statement: FILE *fptr1, *fptr2 ; declares that fptr1 and fptr2 are pointer variables of type FILE. They will be assigned the address of a file descriptor, that is, an area of memory that will be associated with an input or output stream. Whenever you are to read from or write to the file, you must first open the file and assign the address of its file descriptor (or structure) to the file pointer variable.
Testing EOF(end-of-file) is important. Any attempt to read past the end of file might either cause the program to terminate with an error or result in an infinite loop situation.
fprintf
3 parameters :
fp - file pointer associated with a file that has been opened for writing Control string - contains output specification for the items in the list List may include variables , constants , strings
Fprintf ( fptr , %s %d %f , name , age , 7.5 ); Here, name is an array variable of type char and age is an int variable
e.g:
int a = 5, b = 20 ; FILE *fptr2 ; fptr2 = fopen ( "results", "w" ) ; fprintf ( fptr2, "%d %d\n", a, b ) ;
the fprintf functions would write the values stored in a and b to the file "pointed" to by fptr2.
Fscanf Fscanf(fptr , %s %d, item , &quantity); Fscanf also returns the number of items that are successfully read. When the end of file is reached, it returns the value of EOF.
ERROR HANDLING
It is possible that an error may occur during I/O operations on a file. Typical error situation occur: a) Trying to read beyond the end-of-file mark b) Device overflow c) Trying to use a file that has not been opened d) Trying to perform an operation on a file, when the file is opened for another type of operation e) Opening a file with an invalid filename f) Attempting to write to a write-protected file
If we fail to check such read and write errors, a program may behave abnormally when an error occurs. We have two status inquiry library function that help us detect I/O errors in the files: a) feof b) ferror
a) Feof used to test for an EOF condition. it takes a FILE pointer as its only argument and returns a nonzero integer value of all of the data from the specified file has been read and returns zero otherwise E.g if( feof(fptr)) printf( end of data\n); Would display the message end of dat on reaching the end of file condition
b) Ferror reports the status of the file indicated. It also takes a FILE pointer as its argument and returns a nonzero integer if an error has been detected up to that point, during processing . It returns zero otherwise. If(ferror(fptr ) != 0) printf(an error has occurred \n); Would print the error message , if the reading is not successful.
Whenever a file is opened using fopen function , a file pointer is returned. If the file cannot be opened for some reason, then the function returns a NULL pointer. This facility can also be used to test whether a file has been opened or not. If(fp==NULL) printf(file could not be opened \n); e.g: FILE *fptr ; fptr = fopen ( "mydata", "r") ; if (fptr == NULL) { printf ("File 'mydata' did not open.\n") ; }
Closing a file
The input output library supports the function to close a file; it is in the following format. fclose(file_pointer); A file must be closed as soon as all operations on it have been completed. This would close the file associated with the file pointer. Observe the following program. . FILE *p1 *p2; p1=fopen (Input,w); p2=fopen (Output,r); . fclose(p1); fclose(p2) ;
Closing a file will release the file descriptor space and I/O buffer memory.
Example
#include< stdio.h > main() { file *f1; printf(Data input output); f1=fopen(Input,w); while((c=getchar())!=EOF) putc(c,f1); fclose(f1); printf(nData outputn); f1=fopen(INPUT,r); while((c=getc(f1))!=EOF) printf(%c,c); fclose(f1); }
/*Open the file Input*/ /*get a character from key board*/ /*write a character to input*/ /*close the file input*/ /*Reopen the file input*/
Check for feof and ferror functions End_of_File
a) Ftell :
Takes a file pointer and return a number of type long, that corresponds to the current position. This function is useful in saving the current position of a file, which can be used later in the program.
n = ftell(fptr);
n would give the relative offset(in bytes) of the current position. This means n bytes have already been read ( or written)
b) Rewind(): Takes a file pointer and resets the position to the start of the file. rewind(fptr); N= ftell(fptr);
Would assign 0 to n because the file position has been set to the start of the file by rewind(). First byte in file is numbered as 0 then 1 and so on.. Rewind() function helps us in reading file more than once, without having to close and open the file. Whenever a file is opened for reading and writing rewind is done implicitly.
Fseek(): Used to move the file position to a desired location within the file fseek(file pointer,offset, position); File pointer : - pointer to the file concerned. Offset:- number or variable of type long Offset specifies the number of positions (bytes) to be moved from the location specified by the position. Offset may be positive ,meaning moving forward or negative , moving backwards position:- an integer number. The position can take the 3 values. 0 Beginning of the file 1 Current position 2 End of file.
When the operation is successful, fseek returns a zero. If we attempt to move the file pointer beyond boundaries, an error occurs and fseek returns -1 (minus one)
MEANING Go to the beginning (similar to the rewind) Stay at the current position ( rarely used) Go to the EOF , past the last character of the file Move to (m+1)th byte in the file
Fseek(fp,m,1) Fseek(fp,-m,1)
Fseek(fp,-m,2)