Purpose

The lseek function is used to change the position of a file pointer (identified by a handle).

Header Files

io.h
(lseek)
errno.h
(errno values)

Prototype

long lseek (int Handle, long Offset, int Origin);

Arguments

Handle
Selector (file descriptor) of an open file.
Offset
The (signed) number of bytes by which the file pointer is to be positioned from the origin.
Origin
The reference position.  One of:
SEEK_SET
Beginning of file
SEEK_CUR
Current file position
SEEK_END
End of file

Return Values

>=0
Current number of bytes by which the file pointer is positioned from the origin..
-1
The seek failed.

Side Effect

errno
Iff the lseek fails, the global variable errno is set to one of:
EBADF
Handle not open
EINVAL
Invalid Origin value

Example

#include <stdio.h>
#include <io.h> 
#include <fcntl.h>
#include <errno.h>

int main () {
  int Account_Master;
  char Buffer [100]; 
  int Maximum; 
  int Actual;
  /* Other declarations */
  Maximum = 100;
  Account_Master = open ("accounts.dat", O_RDWR);
  if (Account_Master >0) {
    printf ("Open succeeded.\n");
  } else {
    printf ("Open failed.\n")
    switch (errno) {
      case EACCES:  printf ("Permission denied.\n"); break;
      case EINVACC: printf ("Invalid access mode.\n"); break;
      case EMFILE:  printf ("No file handle available.\n"); break;
      case ENOENT:  printf ("File or path not found.\n"); break;
      default:      printf ("Unknown error.\n"); break;
    }
  /* File processing */
  while (!eof (Account_Master)) {
    Pos = tell (Account_Master);
    Actual = read (Account_Master, Buffer, Maximum);
    /* MODIFY THE RECORD */
    /* rewrite the record */
    lseek (Account_Master, Pos, SEEK_SET);
    Actual = write (Account_Master, Buffer, Maximum);
  }
  if (close (Account_Master) == 0) {
    printf ("Close succeeded.\n");
  } else {
    printf ("Close failed.\n")
    switch (errno) {
      case EBADF:  printf ("File not open.\n"); break;
      default:     printf ("Unknown error.\n"); break;
    }
  }
  return 0;
}

See Also

read   Read a file

Valid HTML 4.01 Transitional

Valid CSS

Site Icon Copyright © 1999-2007, jhyoung, revised 4/14/2007