DR29
DR29

Reputation: 121

Creating a file with a hole

I was trying to create a file with a hole using a textbook code and modifying it slightly. However, something must've gone wrong, since I don't see any difference between both files in terms of size and disk blocks.

Code to create a file with a hole (Advanced Programming in the Unix Environment)

#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);
}

My code, creating a file basically full of abcdefghij's.

#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);
}

Printing both files I get the expected output. However, their size is identical.

{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

Upvotes: 2

Views: 3035

Answers (1)

dbush
dbush

Reputation: 223739

You misunderstand what is meant by a "hole".

What it means is that you write some number of bytes, skip over some other number of bytes, then write more bytes. The bytes you don't explicitly write in between are set to 0.

The file itself doesn't have a hole in it, i.e. two separate sections. It just has bytes with 0 in them.

If you were to look at the contents of the first file, you'll see it has "abcdefghij" followed by 16373 (16384 - 10 - 1) bytes containing the value 0 (not the character "0") followed by ABCDEFGHIJ.

Upvotes: 1

Related Questions