【发布时间】:2018-09-24 17:53:31
【问题描述】:
我使用的系统是Linux。
代码:
#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);
}
结果:
“f3.txt”文件内容为“123456789”。
众所周知:
如果内容是123456789
对应的索引是012345678
lseek(fd1,0,SEEK_END) 的值应该等于'9',而不是'10'(基于SEEK_END的解释:文件末尾的偏移量),这让我很困惑很多。 为什么?
文件内容图片:
以及命令'wc'的结果:
【问题讨论】:
-
文件的内容真的是“123456789”还是在末尾包含换行符,例如“123456789\n”?
-
我将把 Janne 的问题改写为答案。这是因为您的文本文件有一个尾随换行符(十六进制:0x0A)。运行“ls f3.txt -l”并自己确认文件大小为10。
-
@MatthewM。我会让那个“运行
ls -l f3.txt”。 -
@SteveSummit 果然,我尝试了两种变体......并且“ls”的输出是相同的。