0

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>

Ryoma
  • 11
  • 5

1 Answers1

1

Solved issue by adding

#include <unistd.h>
Ryoma
  • 11
  • 5
  • This solution indicates that you didn't have a proper declaration of the `lseek` function. If the compiler didn't warn you about it, then consider enabling more warnings when building. I recommend at least the `-Wall` flag. Personally I use at least `-Wall -Wextra -Wpedantic`. – Some programmer dude Sep 10 '20 at 12:05
  • Thank you for the suggestion. I've added them and realized another import that I needed for an assignment. – Ryoma Sep 10 '20 at 21:29