lseek() sample program in C
By: Baski
Input and output are normally sequential: each read or write takes place at a position in the file right after the previous one. When necessary, however, a file can be read or written in any arbitrary order. The system call lseek provides a way to move around in a file without reading or writing any data:long lseek(int fd, long offset, int origin);sets the current position in the file whose descriptor is fd to offset, which is taken relative to the location specified by origin. Subsequent reading or writing will begin at that position. origin can be 0, 1, or 2 to specify that offset is to be measured from the beginning, from the current position, or from the end of the file respectively. For example, to append to a file (the redirection >> in the UNIX shell, or "a" for fopen), seek to the end before writing:
lseek(fd, 0L, 2);To get back to the beginning (``rewind''),
lseek(fd, 0L, 0);Notice the 0L argument; it could also be written as (long) 0 or just as 0 if lseek is properly declared.
With lseek, it is possible to treat files more or less like arrays, at the price of slower access. For example, the following function reads any number of bytes from any arbitrary place in a file. It returns the number read, or -1 on error.
#include "syscalls.h" /*get: read n bytes from position pos */ int get(int fd, long pos, char *buf, int n) { if (lseek(fd, pos, 0) >= 0) /* get to pos */ return read(fd, buf, n); else return -1; }The return value from lseek is a long that gives the new position in the file, or -1 if an error occurs. The standard library function fseek is similar to lseek except that the first argument is a FILE * and the return is non-zero if an error occurred.
Archived Comments
1. Thank you, that was short and enough :)
View Tutorial By: Bilal korir at 2014-05-20 21:37:12
2. Boobs (.)(.)
View Tutorial By: What at 2014-05-05 16:16:28
3. i don't know anything about computer..........
View Tutorial By: Ami weds Pappu....... at 2013-02-14 04:00:11
4. i like google
View Tutorial By: parikh dhruti at 2013-02-12 06:43:19
5. To determine current location in a file:
{
if (lseek(STDIN_FILENO, 0, SEEK_CUR) == -1
View Tutorial By: Terry at 2009-09-27 13:15:56
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
Sum of the elements of an array in C
Printing a simple histogram in C
Find square and square root for a given number in C
Simple arithmetic calculations in C
Passing double value to a function in C
Passing pointer to a function in C
Infix to Prefix And Postfix in C
while, do while and for loops in C