COHERENT manpages
This page displays the COHERENT manpage for fseek() [Seek on file stream].
List of available manpages
Index
fseek() -- STDIO Function (libc)
Seek on file stream
#include <stdio.h>
int fseek(fp, where, how)
FILE *fp; long where; int how;
fseek() changes where the next read or write operation will occur within
the file stream fp. It handles any effects the seek routine might have had
on the internal buffering strategies of the system. The arguments where
and how specify the desired seek position. where indicates the new seek
position in the file. It is measured from the start of the file if how
equals SEEK_SET (zero), from the current seek position if how equals
SEEK_CUR (one), and from the end of the file if how equals two SEEK_END
(two).
fseek() differs from its cousin lseek() in that lseek() is a COHERENT
system call and takes a file number, whereas fseek() is a STDIO function
and takes a FILE pointer.
Example
This example opens file argv[1] and prints its last argv[2] characters
(default, 100). It demonstrates the functions fseek(), ftell(), and
fclose().
#include <stdio.h>
extern long atol();
void fatal(message)
char *message;
{
fprintf(stderr, "tail: %s\n", message);
exit(1);
}
main(argc, argv)
int argc; char *argv[];
{
register FILE *ifp;
register int c;
long nchars, size;
if (argc < 2 || argc > 3)
fatal("Usage: tail file [ nchars ]");
nchars = (argc == 3) ? atol(argv[2]) : 100L;
if ((ifp = fopen(argv[1], "r")) == NULL)
fatal("cannot open input file");
/* Seek to end */
if (fseek(ifp, 0L, 2) == -1)
fatal("seek error");
/* Find current size */
size = ftell(ifp);
size = (size < nchars) ? 0L : size - nchars;
/* Seek to point */
if (fseek(ifp, size, 0) == -1)
fatal("seek error");
while ((c = getc(ifp)) != EOF)
/* Copy rest to stdout */
putchar(c);
if (fclose(ifp) == EOF)
fatal("cannot close");
exit(0);
}
See Also
fsetpos(),
ftell(),
libc,
lseek()
ANSI Standard, §7.9.9.2
POSIX Standard, §8.1
Diagnostics
For any diagnostic error, fseek() returns -1; otherwise, it returns zero.
If fseek() goes beyond the end of the file, it will not return an error
message until the corresponding read or write is performed.