Why am I getting such accurate results from `filesize`?

When I run this code:

<?php $handle = fopen('/tmp/lolwut', 'w') or die("Cannot open File"); fwrite($handle, "1234567890"); fclose($handle); print_r(filesize('/tmp/lolwut')); ?> 

I get a result of 10 , which is the correct number of characters in the file.

However, since the file system blocks are much larger, I expected the file size to be rounded to more than 512 bytes, or even 1 KB. Why is this not so?

+4
source share
1 answer

Do not confuse "file size" with "file size on disk"; The PHP filesize function gives you the first, not the last.

Although it is not explicitly documented as such, filesize is mostly implemented from the stat point of view, and on Linux stat , a distinction is made between file size and file size on disk " :

All of these system calls return a stat structure that 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 */ // [...] }; 

The expected value is st_blocks * st_blksize , but the "true" file size of st_size is available independently.

( This is similar to Windows, too .)

+8
source

Source: https://habr.com/ru/post/1479707/


All Articles