File
Positions: ftell() and fseek()
ftell() tells a program its position within a file, opened by fopen(). fseek() seeks a specified place within a file, opened by fopen(). Normally high level read/write functions perform as much
management over positions inside files as the programmer wants, but in the
event of their being insufficient, these two routines can be used. The form of
the function calls is:
long
int pos;
FILE
*fp;
pos
= ftell(fp);
fp is an open file, which is in some state of being read or
written to. pos is a long integer value which describes the position in
terms of the number of characters from the beginning of the file. Aligning a
file portal with a particular place in a file is more sophisticated than simply
taking note of the current position. The call to fseek() looks
like this:
long
int pos;
int
mode,returncode;
FILE
*fp;
returncode
= fseek (fp,pos,mode);
The parameters have the following
meanings. fp is a pointer to a file opened by fopen(). pos is some way of describing the position required within
a file. mode is an integer which specifies the way in which pos is to be
interpreted. Finally, returncode is an integer whose value is 0 if the operation was
successful and -1 if there was an error.
0
pos
is an offset measured relative to the beginning of the file.
1
pos
is an offset measured relative to the current position.
2
pos
is an offset measured relative to the end of the file.
Some examples help to show how this
works in practice:
long
int pos = 50;
int
mode = 0,returncode;
FILE
*fp;
if
(fseek (fp,pos,mode) != 0) /* find 50th character */
{
printf("Error!\n");
}
fseek(fp,0L,0); /* find beginning of file */
fseek(fp,2L,0); /* find the end of a file */
if
(fseek (fp,10L,1) != 0) /* move 10
char's forward */
{
printf("Error!\n");
}
The L's indicate long
constants.
0 comments:
Post a Comment