创建一个带孔的文件

时间:2016-09-14 16:51:51

标签: c unix filesystems

我试图使用教科书代码创建一个带孔的文件并稍微修改它。但是,有些事情必定会出错,因为我没有看到两个文件在大小和磁盘块方面有任何差异。

创建带孔的文件的代码(Unix环境下的高级编程)

#include "apue.h"
#include <fcntl.h>

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

int
main(void)
{
    int     fd;

    if ((fd = creat("file.hole", FILE_MODE)) < 0)
        printf("creat error");

    if (write(fd, buf1, 10) != 10)
        printf("buf1 write error");
    /* offset now = 10 */

    if (lseek(fd, 16384, SEEK_SET) == -1)
        printf("lseek error");
    /* offset now = 16384 */

    if (write(fd, buf2, 10) != 10)
        printf("buf2 write error");
    /* offset now = 16394 */

    exit(0);
}

我的代码,创建一个基本上充满了abcdefghij的文件。

#include "apue.h"
#include <fcntl.h>
#include<unistd.h>

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

int
main(void)
{
    int     fd;

    if ((fd = creat("file.nohole", FILE_MODE)) < 0)
        printf("creat error");

    while(lseek(fd,0,SEEK_CUR)<16394)
    {
        if (write(fd, buf1, 10) != 10)
        printf("buf1 write error");
    }

    exit(0);
}

打印两个文件我得到了预期的输出。但是,它们的大小是相同的。

{linux1:~/dir} ls -ls *hole
17 -rw-------+ 1 user se 16394 Sep 14 11:42 file.hole
17 -rw-------+ 1 user se 16400 Sep 14 11:33 file.nohole

1 个答案:

答案 0 :(得分:1)

你误解了“洞”的含义。

这意味着您编写一些字节数,跳过其他一些字节数,然后写入更多字节。您未明确写入的字节数设置为0.

文件本身没有洞,即两个独立的部分。它只有字节,其中包含0。

如果您要查看第一个文件的内容,您会看到它有“abcdefghij”后跟16373(16384 - 10 - 1)个字节,其中包含值0(不是字符“0”),后跟ABCDEFGHIJ。