-1

The system i am using is Linux.

Code:

#include<stdio.h>
#include<sys/stat.h>
#include<fcntl.h>

void main()
{
    int rbytes,wbytes,fd1,local;
    char buf[10],ch;
    fd1=open("f3.txt",O_RDONLY,0);
    local=lseek(fd1,0,SEEK_CUR);
    printf("The start file pointer position:%d\n",local);
    local=lseek(fd1,0,SEEK_END);
    printf("End pointer position:%d\n",local);
    local=lseek(fd1,-10,SEEK_END);
    printf("-10 File pointer location:%d\n",local);
    rbytes=read(fd1,buf,5);
    buf[5]='\0';
    printf("buf=%s\n",buf);
    close(fd1);
}

Result:

enter image description here

The file's content of "f3.txt" is "123456789".

As we all know:

if the content is 123456789

the corresponding index is 012345678

The value of lseek(fd1,0,SEEK_END) should be equal to '9', instead of '10'(base on the explanation of SEEK_END: the offset to the end of file), which confuse me a lot. Why?

The image of file content:

The image of file content

And the result of command 'wc':

And the result of command 'wc'

egochen
  • 1
  • 2
  • Is the file's contents really "123456789" or does it include a newline at the end, e.g. "123456789\n"? – Janne Husberg Apr 14 '18 at 14:59
  • I'm going to rephrase Janne's question as the answer. It's because your text-file has a trailing line-feed (hex: 0x0A). Run "ls f3.txt -l" and confirm for yourself that the file size is 10. – Matthew M. Apr 14 '18 at 15:12
  • 2
    @MatthewM. I'd make that "run `ls -l f3.txt`". – Steve Summit Apr 14 '18 at 15:16
  • [How to view files in binary in the terminal?](https://stackoverflow.com/q/1765311/608639), [Show Hexadecimal Numbers Of a File](https://stackoverflow.com/q/2003803/608639), etc. – jww Apr 14 '18 at 15:45
  • @SteveSummit Sure enough, I tried both variants... and the outputs of "ls" were identical. – Matthew M. Apr 14 '18 at 15:53
  • copy text output and paste here, not in images – phuclv Apr 14 '18 at 15:57
  • @MatthewM. Most Unix/Linux systems (though evidently not yours) require that options precede the filenames. When I try `ls f3.txt -l` on my system, I get "`ls: -l: No such file or directory`", because it treats `-l` at the end as another filename, not an option flag. – Steve Summit Apr 14 '18 at 20:19
  • Neither Ubuntu, Mint, nor RHEL7 take issue with it. That would cover quite a bit of Linux installations in 2018. – Matthew M. Apr 18 '18 at 13:28

1 Answers1

2

If you created f3.txt using vi and putted 123456789 by default one new line char \n added at end of line thats why local=lseek(fd1,0,SEEK_END); returns 10 that means plus one for newline.

you can run wc f3.txt on command line and can verify.

Achal
  • 11,821
  • 2
  • 15
  • 37