Random
Access File
Normally data in file read in sequential manner , but if need to access
only a particular part of a file and not reading the other part. For that
random access functions like fseek() ,
ftell() and rewind() available in I/O library.
ftell()
This function returns relative offset (in bytes ) of the current
position of a file. This function useful in saving the current position of a
file , which can be used later in
program.
Syntax:
long
ftell(File-ptr);
As shown in above syntax File-ptr is the pointer to the file structure.
It returns the current
file position of the given stream. If it is a binary stream, then the value is
the number of bytes from the beginning of the file. If it is a text stream,
then the value is a value useable by the fseek() function to return the file
position to the current position.
Ex,
long
n= ftell(fp);
Here, variable n stores the
current position and n bytes have already been read and written.
fseek()
This function is used to move file position to a desire location within
a file.
Syntax:
fseek(File-ptr,offset,position);
Here, File-ptr is the pointer
to the file.
Offset specifies the number of positions (byte) to be moved from the location
specified by position. Offset is a number or variable of long data type.
Position is an integer number. It has following three values.
Value
|
Meaning
|
0
Or SEEK_SET
|
Beginning of file
|
1
Or SEEK_CUR
|
Current position
|
2
Or SEEK_END
|
End of file
|
If offset is positive , it moves file pointer in forward direction. If
offet is negative , it moves file pointer in backward direction.
This function returns zero if operation is successful. If the file
pointer is end of file means EOF and though file pointer tries to move data
then error occurs and returns -1
Operations of
fseek()
Statement
|
Meaning
|
feek(fp,0L,0)
|
Go to the beginning.
|
feek(fp,0L,1)
|
Stay at current position.
|
feek(fp,0L,2)
|
Go to the end of file.
|
feek(fp,m,0)
|
Move (m+1) th byte in the file.
|
feek(fp,m,1)
|
Go forward by m bytes
|
feek(fp,-m,1)
|
Go backward by m bytes from current position
|
feek(fp,-m,2)
|
Go backward by m bytes from the end.
|
rewind()
This function resets the file position to the beginning of the file.
Syntax:
void rewind(File-ptr);
Here, File pointer is the pointer to file structure.
Ex,
rewind(fp);
long n=ftell(fp);
In above example it will assigns 0 to n because the file position has
been set to the start of the file.
With the use of this function , without closing or opening a file , file
can be read more then one time. File is opened fpr both reading and writing.
Posted By : Ruchita Pandya
No comments:
Post a Comment