Binary Files 1
Binary Files 1
w (write mode):
Used to create a file.
Used only for text file.
If the file does not exists, a file is created.
If file already exists, original contents of file are
lost.
File pointer points at the beginning.
a (append mode):
Used to insert data at the end of existing file.
Used only for text file.
If file does not exists, a file is created.
If already exists, file pointer points to the end.
The new data is inserted at the end.
Existing data cannot be modified.
wb (write mode):
Used to create a file.
Used only for binary file.
If the file does not exists, a file is created.
If file already exists, original contents of file are
lost.
File pointer points at the beginning.
ab (append mode):
Used to insert data at the end of existing file.
Used only for binary file.
If file does not exists, a file is created.
If already exists, file pointer points to the end.
The new data is inserted at the end.
Existing data cannot be modified.
On success: return fp
On failure : returnNULL
feof() Function
Detecting the End of a File Using the feof()
Function :
◦ To detect end-of-file, there is library function feof(),
which can be used for both binary- and text-mode files.
◦ int feof(FILE *fp);
◦ The argument fp is the FILE pointer returned by
fopen() when the file was opened.
◦ The function feof() returns 0 if the end-of-file has not
been reached, or a non-zero value if end-of-file has
been reached.
ferror( ) :
Used to detect an erroroccured during
read/write operation on a file.
Syntax: int ferror(FILE *fp);
Return true (non-zero value) if error is detected.
Returns false(zero value) if an error is not
detected.
clearerr( ) :
Once an error occurs, the subsequent calls to
ferror() returns true until the error status is
cleared.
So, to clear the error statusclearerr( ) is used.
Syntax: void clearer(FILE *fp);
File positioning functions:
File positioning functions are required in the
following scenarios:
1. For accessing the random data from file.
2. For changing the state of the file ( from read to
write / from write to read).
Types of file positioning functions:
◦ 1. rewind( )
◦ 2. ftell( )
◦ 3. fseek( )
rewind( ) : When the data is written into the
file, file has to be opened in write mode, then
data will be written and hence the fp points to
the end of the file. But, when data it to be
read from the file,we have to start reading
from beginning.
- In such situations, we may have to close and
open the file again so that fp ponts to the
beginnig. Instead we can use rewind( ) as it
sets the fp to the beginning without closing
the file.
- Used to set the fp to the beginning of the file.