-3
unsigned int file = open(argv[1], O_RDONLY);

printf("%u\n", file);
printf("%u\n", elf.offset);

lseek(file, elf.offset, SEEK_SET);

printf("%u", file);

OutPut:

3
52
3

Shouldn't file be set to 52?

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
csguy
  • 1,354
  • 2
  • 17
  • 37
  • 1
    No: `file` is a file descriptor. The position of the file pointer has nothing to do with that. Use the return value from `lseek` to obtain the actual position. Read the documentation for `lseek`, and `open` for that matter. You can get the current position by calling `lseek(file, 0, SEEK_CUR)` – paddy Nov 02 '20 at 02:15
  • if `file` contains the offset the how can multiple files can be opened in a single program? – phuclv Nov 02 '20 at 03:16
  • `open()` return an `int` result. Why are you assigning that result to an `unsigned int` object? (I have no idea why you'd expect `file` to be set to 52.) – Keith Thompson Nov 02 '20 at 03:19

3 Answers3

1

file is a file descriptor. When you print it, you print the file descriptor, not the offset. When you lseek it to an offset of 52, the file descriptor is still 3, so it still prints 3.

You can read more about file descriptors here.

Aplet123
  • 33,825
  • 1
  • 29
  • 55
1

Upon successful completion, the resulting offset, as measured in bytes from the beginning of the file, shall be returned.

try this printf("lseek_offset: %d\n", lseek(file, elf.offset, SEEK_SET));

csavvy
  • 761
  • 4
  • 13
1

yon confuse file with file decriptor. The latter is just a non-negative integer that identifies an open file. maybe this example can help you to understand these two concepts better:

char buf[8];
int main(){
    int fd = open("test", O_RDONLY);
    off_t offset = lseek(fd, 0, SEEK_CUR);
    read(fd, buf, sizeof buf);
    printf("first read when offset = %d : %s\n", (int)offset, buf);

    offset = lseek(fd, 32, SEEK_SET);
    read(fd, buf, sizeof buf);
    printf("second read when offset = %d : %s\n", (int)offset, buf);

    return 0;
}

and the output is:

first read when offset = 0 : 0000000

second read when offset = 32 : 4444444

here are the contents of test:

0000000\n    
1111111\n
2222222\n
3333333\n
4444444\n
nathan
  • 11
  • 1