Search code examples
clseek

lseek SEEK_END doesn't get last character


FIXED (SEE FINAL EDIT)

I am trying to get the last character of a file using lseek and read. The file I'm opening is this (no '\n' at the end):

the quick brown fox jumps over the lazy dog

I want the output to be 'd'. For some reason, doing lseek(file, -1, SEEK_END) does not seem to work. However, adding a redundant lseek(file, position, SEEK_SET) after it works. My code:

int file;
char c;
int position;

/*************** Attempt 1 (does not work) ***************/

file = open("test", O_RDONLY);
position = lseek(file, -1, SEEK_END);
printf("lseek returns %i\n", position);
printf("read returns %i\n", read(file, &c, 1));
printf("last character is \"%c\"\n\n", c);
close(file);

/********* Attempt 2 (seems redundant but works) *********/

file = open("test", O_RDONLY);
position = lseek(file, -1, SEEK_END);
printf("lseek returns %i\n", position);

/* ADDED LINES */
position = lseek(file, position, SEEK_SET);
printf("lseek returns %i\n", position);

printf("read returns %i\n", read(file, &c, 1));
printf("last character is \"%c\"\n\n", c);
close(file);

Gives an output:

lseek returns 42
read returns 0
last character is ""

lseek returns 42
lseek returns 42
read returns 1
last character is "g"

Does anyone know what's happening?


Edit: I've tried lseek(file, 0, SEEK_CUR) in place of lseek(file, position, 0) and it does not work, although it still returns 42.

Edit 2: Removed magic numbers.


Final edit: Fixed by adding #include <unistd.h>


Solution

  • Solved issue by adding

    #include <unistd.h>