du和ls查看文件大小的区别
文件中的空洞并不要求在磁盘上占用存储区。具体处理方式与文件系统的实现有关,当定位超出文件尾端之后写时,对于新写的数据需要分配磁盘块,但是对于原文件尾端和新开始写位置之间的部分则不需要分配磁盘块。
例如:用dd if=/dev/zero of=a.out seek=1023 bs=1M count=1创建a.out文件后,用ls查看a.out的文件大小为1G,用du查看a.out文件大小为1M。
生成黑洞文件的示例代码temp.c:
#include
#include
#include
#define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
char buf1[] = "abcdefghij";
char buf2[] = "ABCDEFGHIJ";
void err_sys(char *msg){
printf("%s", msg);
exit(0);
}
int main(void){
int fd;
if((fd = creat("file.hole", FILE_MODE)) < 0)
err_sys("creat error");
if(write(fd, buf1, 10) != 10)
err_sys("buf1 write error");
if(lseek(fd, 16384, SEEK_SET) == -1)
err_sys("lseek error");
if(write(fd, buf2, 10) != 10)
err_sys("buf2 write error");
exit(0);
}
$gcc temp.c
$./a.out
$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
*
0040000 A B C D E F G H I J
0040012
$du -sh file.hole
8.0K file.hole
$ls -al
drwxr-xr-x 2 root root 4096 Apr 15 20:20 .
drwxr-xr-x 8 root root 4096 Mar 20 13:22 ..
-rwxr-xr-x 1 root root 5598 Apr 15 20:20 a.out
-rw-r--r-- 1 root root 16394 Apr 15 20:20 file.hole
-rw-r--r-- 1 root root 718 Apr 15 20:20 temp.c