Lseek not working

2k views Asked by At

i am trying to check the size of my txt files using lseek. Unfortunately i doesnt work. My T.Txt contains 16 characters:ABCDABCDDABCDABCD nothing more. So the number variables should have 16+1. Why it is 19 instead? The second problem why i cant use SEEK_END-1 to start from last position-1.? I would be grateful for help with that.

int main(void)
{
    int fd1 = open("T.txt", O_RDONLY);
    long  number;

    if (fd1 < 0) {
        return -1;
    }

    number = lseek(fd1, 0, SEEK_END); 
    printf("FILE size PROGRAM>C: %ld\n", number);

return 0;
}
2

There are 2 answers

2
syntagma On BEST ANSWER

This is probably because of the \r\n characters in your file, which stand for newline on Windows systems.

On my machine (Mac OS X 10.10) your code gives the right result for your file, provided it doesn't have any newline character on the end, i.e. only the string: ABCDABCDDABCDABCD (output is then: 17).

You use the lseek() function correctly except that the result of lseek() is off_t not a long.

0
DivyananD rangu On

Probably your text file contains a BOM header 0xEF,0xBB,0xBF. Try to print the file contents in HEX and see if it prints these extra 3 characters.

You can learn more about [file headers and BOM here].(https://en.wikipedia.org/wiki/Byte_order_mark)