【问题标题】:Why is lseek(fd1,0,SEEK_END) equal file size + 1?为什么 lseek(fd1,0,SEEK_END) 等于文件大小 + 1?
【发布时间】: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的解释:文件末尾的偏移量),这让我很困惑很多。 为什么?

文件内容图片:

The image of file content

以及命令'wc'的结果:

And the result of command 'wc'

【问题讨论】:

  • 文件的内容真的是“123456789”还是在末尾包含换行符,例如“123456789\n”?
  • 我将把 Janne 的问题改写为答案。这是因为您的文本文件有一个尾随换行符(十六进制:0x0A)。运行“ls f3.txt -l”并自己确认文件大小为10。
  • @MatthewM。我会让那个“运行ls -l f3.txt”。
  • @SteveSummit 果然,我尝试了两种变体......并且“ls”的输出是相同的。

标签: c linux fseek


【解决方案1】:

如果您使用vi 创建f3.txt 并默认放置123456789,则在行尾添加一个新行字符\n,这就是local=lseek(fd1,0,SEEK_END); 返回10 的原因,这意味着newline 加一。

您可以在命令行上运行wc f3.txt 并进行验证。

【讨论】:

  • @egochen 它表明你做到了。这就是为什么wc 说 10 而不是 9。
  • 在某种程度上,这个问题已经解决了。谢谢大家!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-17
  • 1970-01-01
  • 2019-01-31
  • 2013-01-05
  • 1970-01-01
  • 2022-04-12
  • 1970-01-01
相关资源
最近更新 更多