C:关于使用偏移超过当前seek_set的lseek系统调用

时间:2013-06-16 13:42:04

标签: c linux unix system-calls seek

代码来自

char buf1[] = "abcdefghij";
char buf2[] = "ABCDEFGHIJ";

int
main(int argc, char *argv[])
{
    int fd;

    if((fd = creat("file.hole", 0777)) < 0)
        perror("creat error");

    if(write(fd, buf1, 10) != 10)
        perror("buf1 write error");
    if(lseek(fd, 04000, SEEK_SET) == -1)
        perror("lseek error");

    if(write(fd, buf2, 10) != 10)
        perror("buf2 write error");

    exit(EXIT_SUCCESS);
}

通过

读取文件
  

od -c file.hole

和输出:

0000000   a   b   c   d   e   f   g   h   i   j  \0  \0  \0  \0  \0  \0
0000020  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0  \0
*
0004000   A   B   C   D   E   F   G   H   I   J
0004012

如果我删除lseek,并创建file.nohole,则输出将为

0000000   a   b   c   d   e   f   g   h   i   j   A   B   C   D   E   F
0000020   G   H   I   J
0000024

有两个问题让我困惑。

> 1.At output1, why there are 30 * '\0' after j
> 2.output1: why file ends with 0004012 not 0004010

1 个答案:

答案 0 :(得分:2)

  

1.在输出1,为什么在j

之后有30 *'\ 0'

不是30,但差不多是04000. od截断了输出,因为它非常重复。为什么有零?因为你告诉你的程序插入它们。 lseek()填充了该文件。

  

为什么文件以0004012而非0004010

结尾

它没有 - 它再次od以八进制打印地址,而不是十六进制(正如您所预期的那样)。