Question

Code is from

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

read file by

od -c file.hole

and Output:

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

if i remove lseek , and creat file.nohole, the output will be

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

There are two problem make me confused.

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

Solution

1.At output1, why there are 30 * '\0' after j

Not 30, but almost 04000. od truncated the output because it was huge and repetitive. Why are there zeroes? Because you told your program to insert them. lseek() padded the file.

why file ends with 0004012 not 0004010

It doesn't - it's again od prints addresses in octal, not in hexadecimal (as you may have expected).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top