Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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 the result 10, which is the correct number of characters in the file.

However, because filesystem blocks are much larger than this, I expected the file size to be "rounded up" to more like 512 bytes or even 1KB. Why is it not?

like image 628
Lightness Races in Orbit Avatar asked Feb 17 '23 14:02

Lightness Races in Orbit


1 Answers

Do not confuse "file size" for "file size on disk"; PHP's filesize function gives you the former, not the latter.

Although not explicitly documented as such, filesize is basically implemented in terms of stat, and on 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 */
    // [...]
};

The value you're expecting is st_blocks * st_blksize, but the "true" filesize st_size is available regardless.

(This appears to be the case on Windows, too.)

like image 180
Lightness Races in Orbit Avatar answered Mar 05 '23 00:03

Lightness Races in Orbit