COHERENT manpages
This page displays the COHERENT manpage for fgetpos() [Get value of file-position indicator].
List of available manpages
Index
fgetpos() -- STDIO Function (libc)
Get value of file-position indicator
#include <stdio.h>
int
fgetpos(fp, position)
FILE *fp; fpos_t *position;
fgetpos() copies the value of the file-position indicator for the file
stream pointed to by fp into the area pointed to by position. position is
of type fpos_t, which is defined in the header stdio.h.
The function fsetpos() can use the information written into position to
return the file-position indicator to where it was when fgetpos() was
called.
fgetpos() returns zero if all went well. If an error occurred, it returns
nonzero and sets errno to an appropriate value.
Example
This example seeks to a random line in a very large file.
#include <math.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void
fatal(message)
char *message;
{
fprintf(stderr, "%s\n", message);
exit(1);
}
main(argc, argv)
int argc; char *argv[];
{
int c;
long count;
FILE *ifp, *tmp;
fpos_t loc;
if (argc != 2)
fatal("usage: fscanf inputfile\n");
if ((ifp = fopen(argv[1], "r")) == NULL)
fatal("Cannot open %s\n", argv[1]);
if((tmp = tmpfile()) == NULL)
fatal("Cannot build index file");
/* seed random-number generator */
srand ((unsigned int)time(NULL));
for (count = 1;!feof(ifp); count++) {
/* for monster files */
if (fgetpos(ifp, &loc))
fatal ("fgetpos error");
if (fwrite(&loc, sizeof(loc), 1, tmp) != 1)
fatal("Write fail on index");
rand();
while('\n' != (c = fgetc(ifp)) && EOF != c)
;
}
count = rand() % count;
fseek(tmp, count * sizeof(loc), SEEK_SET);
if(fread(&loc, sizeof(loc), 1, tmp) != 1)
fatal("Read fail on index");
fsetpos(ifp, &loc);
while((c = fgetc(ifp)) != EOF) {
if(c =='@')
putchar('\n');
else
putchar(c);
if(c == '\n')
break;
}
}
See Also
fseek(),
fsetpos(),
ftell(),
libc,
rewind()
ANSI Standard, §7.9.9.1
Notes
The ANSI Standard introduced fgetpos() and fsetpos() to manipulate a file
whose file-position indicator cannot be stored within a long. Under
COHERENT fgetpos() behaves the same as the function ftell().