M F
M F

Reputation: 323

POSIX read() function does not read any bytes when lseek() is called

I have the following program

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>


int main(int argc, char* argv[]) {
    int fd;
    char buffer[100];

    // open notes file
    fd = open("/var/testfile", O_RDONLY); 

    if(fd == -1) {
         error("in main() while opening file for reading");
    }

    int readBytes = 0;

    // read 10 bytes the first time
    readBytes = read(fd, buffer, 10);
    buffer[10] = 0;
    printf("before lseek: %s\n readBytes: %d\n", buffer, readBytes);

    // reset buffer
    int i = 0;
    for(i = 0; i < 10; i++) {
        buffer[i] = 0;
    }

    // go back 10 bytes
    lseek(fd, -10, SEEK_CUR);

    // read bytes second time
    readBytes = read(fd, buffer, 10);
    buffer[10] = 0; 
    printf("after lseek: %s\n readBytes: %d\n", buffer, readBytes);
}

And the following content in the /var/testfile:

This is a test.
A second test line.

The output of the program:

before lseek: This is a 
 readBytes: 10
after lseek: 
 readBytes: 0

I don't unerstand why after the lseek() call the read() function does not read any bytes. What is the reason for this? I would expect the same result as I get from the first read() function call.

Upvotes: 1

Views: 824

Answers (1)

user3710044
user3710044

Reputation: 2334

My compiler says "xxc.c:33:5: warning: implicit declaration of function ‘lseek’ [-Wimplicit-function-declaration]"

This means that the second argument will be assumed to be an integer (probably 32bits), but the definition is actually for the type "off_t" which on Linux or Windows will be a longer 64bit integer.

This means the offset you're giving it is likely to be VERY large and well past the end of your testfile.

The manual says that for lseek() you need the headers:

   #include <sys/types.h>
   #include <unistd.h>

Upvotes: 1

Related Questions