4

I've ran into a scenario where I've created a simple plain text file with just one ASCII letter: a. I checked the file size with stat and here's what I got:

$ stat file
File: 'file'
  Size: 1           Blocks: 8          IO Block: 4096   regular file
Device: 801h/2049d  Inode: 433312      Links: 1
...many details...

Blocks: 8 reported by stat is the number of blocks allocated. Why a file with a 1-byte size file occupies 8 blocks with each block having a size of 4096 bytes?

Assuming I read the results of stat properly, this means other distinct files in the filesystem share blocks, because a 1-byte file consuming 4096 * 8 of space is too much, isn't? Essentially, are the 8 blocks occupied by the 1-byte file alone?

Edit:

This question clarified many concepts: How does stat command calculate the blocks of a file?

Then each block is allocated in 512 bytes and the 1 byte file consumes a physical storage of 512 * 8 = 4096. Does this mean that only one block is actually being used to store the 1 byte and because each block is 512 bytes the block won't be fully used and the remaining 7 blocks will be empty, but still reserved for the 1 byte file?

I/O block as reported by stat is 4096, the 4096 is then the preferable chunks of bytes for reading and writing from and to disk? This indicates that I/O operations read 8 blocks of size 512 bytes at a time, right?.

The physical blocks are always 512 bytes at least for hard drives, is this correct?

GIZ
  • 4,409
  • 1
  • 24
  • 43
  • Possible duplicate of [How does stat command calculate the blocks of a file?](https://stackoverflow.com/questions/1346807/how-does-stat-command-calculate-the-blocks-of-a-file) – Gilles 'SO- stop being evil' Jun 04 '17 at 22:34
  • Short answer: performance reason. Search for difference between character device and block device – Jack Jun 05 '17 at 10:08
  • 1
    So far as I know, ext2/3/4, reiserfs, btrfs would allocate multiple of 4096 bytes for a file. The multiple is equal to `round_up(filesize/4096)`. (4096 is just the `IO Block` you could find in `stat` output). Thus, a file, even if its size is 1 byte, would occupy 4096 bytes, which is 8 blocks if block size is 512 (see `stat`), or 4 blocks if block size is 1024 (see `ls`), or 2 blocks if block size is 2048 (see ??, it's me :). And why is more space allocated for files? I guess so that the file can grow without fragmentation (or in favor of performance?). – Bruce Oct 16 '21 at 07:46
  • Each directory size is also 4096 on those file systems, just as same as the `IO Block`. – Bruce Oct 16 '21 at 08:00
  • These two questions, [file block size - difference between stat and ls](https://unix.stackexchange.com/questions/28780/file-block-size-difference-between-stat-and-ls) and [Understanding IO Block size](https://askubuntu.com/questions/884710/understanding-io-block-size), are also worth reading. – Bruce Oct 16 '21 at 08:02

0 Answers0