fseek

De RAD Studio
Aller à : navigation, rechercher

Remonter à stdio.h - Index

Header File

stdio.h

Category

Input/output Routines

Prototype

int fseek(FILE *stream, long offset, int whence);
int _fseeki64(FILE *stream, __int64 offset, int whence);

Description

Repositions a file pointer on a stream.

fseek sets the file pointer associated with the stream to a new position that is offset bytes from the file location given by whence. For text mode streams offset should be 0 or a value returned by ftell.

whence must be one of the values 0, 1, or 2, which represent three symbolic constants (defined in stdio.h) as follows:

SEEK_SET

0

File beginning

  • If stream is in binary mode, then fseek sets the file pointer to offset bytes from the beginning of the file.
  • If stream is in text mode, then fseek sets the file pointer according to the offset value. offset can be either zero (representing the beginning of the file) or a value returned by an earlier successful call to ftell (representing another position in the file). The offset value is not a byte count, so you cannot add to it or subtract from it.

SEEK_CUR

1

Current file pointer position

  • If stream is in binary mode, then fseek adds offset to the current file pointer value.
  • If stream is in text mode, then the offset must be zero (leaves the file pointer at its current value -- keeping the current position in the file.)

SEEK_END

2

End-of-file

  • If stream is in binary mode, then fseek adds offset bytes from the end of the file (possibly positioning the file pointer after an arbitrary number of null characters).
  • If stream is in text mode, then the offset must be zero (representing the end of the file).

fseek discards any character pushed back using ungetc. fseek is used with stream I/O; for file handle I/O, use lseek.

After fseek, the next operation on an update file can be either input or output.

Return Value

fseek returns 0 if the pointer is successfully moved and nonzero on failure.

In the event of an error return, the global variable errno is set to one of the following values:

EBADF

Bad file pointer

EINVAL

Invalid argument

ESPIPE

Illegal seek on device


Example

#include <stdio.h>
long filesize(FILE *stream);
int main(void)
{
   FILE *stream;
   stream = fopen("MYFILE.TXT", "w+");
   fprintf(stream, "This is a test");
   printf("Filesize of MYFILE.TXT is %ld bytes\n", filesize(stream));
   fclose(stream);
   return 0;
}
long filesize(FILE *stream)
{
   long curpos, length;
   curpos = ftell(stream);
   fseek(stream, 0L, SEEK_END);
   length = ftell(stream);
   fseek(stream, curpos, SEEK_SET);
   return length;
}

Portability

POSIX Win32 ANSI C ANSI C++

+

+

+

+