Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

The GNU C Programming Tutorial - Finding file positions at a low level

Node:Finding file positions at a low level, Next:, Previous:Writing files at a low level, Up:Low-level file routines



Finding file positions at a low level

If you want to find a particular file position within a file, using a low-level file routine, you can call the lseek function. This is very similar to the high-level file routine fseek, except that it accepts a file descriptor rather than a stream as an argument.

The lseek function specifies the file position for the next read or write operation. (See File position, for more information on file positions.)

The lseek function takes three parameters. The first parameter is the file descriptor. The second is of type off_t and specifies the number of bytes to move the file position indicator. The third argument and the third parameter is a constant that specifies whether the offset is relative to the beginning of the file (SEEK_SET), to the current file position (SEEK_CUR), or to the end of the file (SEEK_END). If SEEK_CUR or SEEK_END is used, the offset specified can be positive or negative. If you specify SEEK_END, set the position past the current end of the file, and actually write data, you will extend the file with zeroes up to the position you specify. However, the blocks of zeroes are not actually written to disk, so the file takes up less space on disk than it seems to; this is called a sparse file.

The return value of lseek is of type off_t and normally contains the resulting file position, as measured in bytes from the beginning of the file. If you wish to read the current file position, therefore, you can specify an offset of 0 and a third parameter of SEEK_CUR, as follows:

file_position = lseek (file_descriptor, 0, SEEK_CUR);

If there was an error, lseek returns a -1 and sets the system variable errno to one of the following values:


EBADF
The file descriptor specified is invalid.
EINVAL
Either the third parameter of lseek is invalid, or the file offset is invalid.
ESPIPE
The file descriptor corresponds to an object that cannot be positioned, such as a terminal device.

The lseek function is called by many high-level file position functions, including fseek, rewind, and ftell.

 
 
  Published under free license. Design by Interspire