1

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.

M F
  • 323
  • 1
  • 3
  • 15
  • 1
    Try compiling with `-Wall`. You seem to be missing a prototype for `lseek` (`#include `) which may be your problem. – R.. GitHub STOP HELPING ICE Feb 07 '15 at 14:25
  • Quite so. Probably `off_t` is wider than `int` on your platform (x86-64?), so the implicit `lseek(int, int, int)` declaration will be incompatible. I can reproduce it without the missing `#include` but not with it. – Wintermute Feb 07 '15 at 14:30

1 Answers1

1

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>
user3710044
  • 2,261
  • 15
  • 15