#include <fcntl.h> #include <unistd.h> char buf1[] = "abcdefghij"; char buf2[] = "ABCDEFGHIJ"; char buf3[10]; int main(void) { int fd; if ((fd = creat("file.hole", FILE_MODE)) < 0) { err_sys("creat error"); } if (write(fd, buf1, 10) != 10) { // offset is now = 10 err_sys("buf1 write error"); } if (lseek(fd, 16380, SEEK_SET) == -1) { // offset now = 16380 err_sys("lseek error"); } if (write(fd, buf2, 10) != 10) { // offset now = 16390 err_sys("buf2 write error"); } close(fd); if ((fd = open("file.hole", O_RDWR)) == -1) { err_sys("failed to re-open file"); } ssize_t n; ssize_t m; while ((n = read(fd, buf3, 10)) > 0) { if ((m = write(STDOUT_FILENO, buf3, 10)) != 10) { err_sys("stdout write error"); } } if (n == -1) { err_sys("buf3 read error"); } exit(0); }
I’m newbie in unix system programming
There is code making file with hole.
Output result is:
$ls -ls file.hole file.nohole 8 -rw-r--r-- 1 sar 16394 time file.hole 20 -rw-r--r-- 1 sar 16394 time file.nohole
Why file with hole has fewer disk block than file without hole?
In my thinking, file without hole takes smaller disk blocks
Because file with hole is more spreaded than without hole..
From “Advanced Programming in the UNIX Environment 3rd-Stevens Rago, example 3.2”
Advertisement
Answer
Why do you think that a file without hole takes smaller space ? This exactly the contrary. If the file has holes, then it is not necessary to reserve disk blocks for that space. The number of disk blocks is not related to the spreading of the file, but directly related to the size of the data you wrote in the file.