当我运行这段代码时:
<?php
$handle = fopen('/tmp/lolwut', 'w') or die("Cannot open File");
fwrite($handle, "1234567890");
fclose($handle);
print_r(filesize('/tmp/lolwut'));
?>
我得到结果 10
,这是文件中正确的字符数。
但是,由于文件系统 block 比这大得多,我希望文件大小“四舍五入”到更接近 512 字节甚至 1KB。为什么不是?
最佳答案
不要将“文件大小”与“磁盘上的文件大小”混淆; PHP's filesize
function给你的是前者,而不是后者。
虽然没有明确记录,filesize
基本上是根据 stat
实现的,在 Linux 上 stat
makes a distinction between filesize and "file size on disk" :
All of these system calls return a
stat
structure, which contains the following fields:struct stat { // [...] off_t st_size; /* total size, in bytes */ blksize_t st_blksize; /* blocksize for file system I/O */ blkcnt_t st_blocks; /* number of 512B blocks allocated */ // [...] };
您期望的值是 st_blocks * st_blksize
,但“真实”文件大小 st_size
无论如何都可用。
关于php - 为什么我从 `filesize` 得到如此准确的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16438142/