用ls和du查看一个文件的大小,发现二者显示出来的大小并不一致:
从图片中可以看出,两个相同 的问题使用不同的命令显示的大小不一致。
由于系统中存在几百万的小文件,所以导致两种方式看到的数据文件大小相差很大,一个是几个G,还有一个是几百兆。
du -h 显示的是4.0K,而 ls -ls 显示的是195字节;相差了好几十倍,那么原因究竟是为什么呢?
稀疏文件(sparse file)
ls和du显示出的size有不同的含义
先来看一下稀疏文件。稀疏文件只文件中有“洞”(hole)的文件,例如有C写一个创建有“洞”的文件:
ls和du显示出的size有不同的含义
先来看一下稀疏文件。稀疏文件只文件中有“洞”(hole)的文件,例如有C写一个创建有“洞”的文件:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int fd = open("sparse.file", O_RDWR|O_CREAT);
lseek(fd, 1024, SEEK_CUR);
write(fd, "\0", 1);
return 0;
}
从这个文件可以看出,创建一个有“洞”的文件主要是用lseek移动文件指针超过文件末尾,然后write,这样就形成了一个“洞”。
用Shell也可以创建稀疏文件:
$ dd if=/dev/zero of=sparse_file.img bs=1M seek=1024 count=0
0+0 records in
0+0 records out
使用稀疏文件的优点如下(Wikipedia上的原文):
The advantage of sparse files is that storage is only allocated when actually needed: disk space is saved, and large files can be created even if there is insufficient free space on the file system.
即稀疏文件中的“洞”可以不占存储空间。
$ dd if=/dev/zero of=sparse_file.img bs=1M seek=1024 count=0
0+0 records in
0+0 records out
使用稀疏文件的优点如下(Wikipedia上的原文):
The advantage of sparse files is that storage is only allocated when actually needed: disk space is saved, and large files can be created even if there is insufficient free space on the file system.
即稀疏文件中的“洞”可以不占存储空间。
再来看一下ls和du输出的文件大小的含义(Wikipedia上的原文):
The du command which prints the occupied space, while ls print the apparent size。
换句话说,ls显示文件的“逻辑上”的size,而du显示文件“物理上”的size,即du显示的size是文件在硬盘上占据了多少个block计算出来的。
The du command which prints the occupied space, while ls print the apparent size。
换句话说,ls显示文件的“逻辑上”的size,而du显示文件“物理上”的size,即du显示的size是文件在硬盘上占据了多少个block计算出来的。
所以导致了以上问题的发生,所以以后在查看文件大小一定要慎重选择查看文件的方式,否则有可能影响后期存储决策方案。