Why isn't lseek changing value? (C)

364 Views Asked by At
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?

3

There are 3 best solutions below

0
csavvy On BEST ANSWER

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));

0
Aplet123 On

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.

0
nathan On

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