lseek

Navigation:  Programming language SQC > Built-in functions > Filesystem >

lseek

Previous pageReturn to chapter overviewNext page

The lseek() function repositions the offset of the open file associated with the file descriptor fd to the argument offset

according to the directive whence as follows:

 

 

SEEK_SET

   The offset is set to offset bytes.

 

SEEK_CUR

   The offset is set to its current location plus offset bytes.

 

SEEK_END

   The offset is set to the size of the file plus offset bytes.

 

 

int lseek(int fd,int offset,int whence); 

 

Example :

 

 

#define EMBEDTRON "www.embedtron.com"

#define BUFFER_SIZE 20

 

int main() 

{

    char buffer[BUFFER_SIZE];

    

    int len = 0;

    int fh  = 1;

 

    if((fh=open("file.txt","w" )) == -1) 

    {

        printf("Create file failed");

        return -1;

    }

 

    if((len = write(fh,EMBEDTRON,strlen(EMBEDTRON))) != strlen(EMBEDTRON))

    {

        printf("Write data failed");

        return -2;

    }

 

    close(fh);

    

    if((fh=open("file.txt","r" )) == -1) 

    {

        printf("Create file failed");

        return -1;

    }

 

    lseek(fh, 0, SEEK_END);

    len = tell(fh);

 

    lseek(fh, 0, SEEK_SET);

    if((len = read(fh,buffer,BUFFER_SIZE)) != strlen(EMBEDTRON))

    {

        printf("Read data failed");

        return -3;

    }

 

    buffer[len] = '\0';

 

    printf("String = %s Size = %d \n",buffer,len);

    

    close(fh);

    

    return 0;

 }