ERROR HANDLING DURING I/O OPERATIONS
ERROR HANDLING DURING I/O OPERATIONS
It is possible
that an error may occur during I/O operations on a file.
Typical error
situations include:1. Trying to read beyond the end-of-file mark.
2. Device overflow.
3. Trying to use a file that has not been opened.
4. Trying to perform an operation on a file, when the file is opened for
another type of operation.
5. Opening a file with an invalid filename.
6. Attempting to write to a write-protected file.
RANDOM ACCESS
TO FILES
We have
discussed file functions that are useful for reading and writing data
sequentially. There are occations, however, when we are interested in accessing
only a particular part of a file and not in reading the other parts. This can
be achieved with the help of the functions fseek, ftell, and rewind
available in the I/O library, ftell takes a
file pointer and returns a number of type long, that corresponds to the current
position. This function is useful in saving thecurrent position of a file,
which can be used later in the program. It takes the following form:
n = ftell(fp);
n would give
the relative offset (in bytes) of the current position. This means
that n bytes
have already been read (or written). rewind takes a file pointer and resets the
position to the start of the file.For example, the statement
rewind(fp);
n = ftell(fp);
would assign 0 to n because the file position has been set to the start of the file by rewind. Rememer, the first byte in the file is numbered as 0, second as 1, and so on. This function helps us in reading a file more than once, without
having to close and open the file. Remember that whenever a file is opened for reading or writing, a rewind is done implicity. fseek function is used to move the file position to a desired location within the file. It takes the following form:
fseek(file ptr,
offset, position);
file ptr is
a pointer to the file concerned, offset is a number or variable of type long,
and position is an integer number. The offset specifies the number of positions
(bytes) to be moved from the location specified by position. The position can
take one of the following three values:
Value Meaning
0 Beginning of file
1 Current position2 End of file
Comments
Post a Comment