How does ls calculate file size
The ls command can display the file size with the -s or -l switches. Where does it read this information from?
I know the du command recalculates file size by reading the file directly. Does the ls command do this or does it read the file size from the inode? |
I'm 99-44/100% sure it uses stat(); see man 2 stat.
Hope this helps some. |
I get the feeling ls only reads the i-node or file allocation table and does not compute sizes. I could be way wrong on that.
|
strace might be instructive - especially a comparison of "ls" versus "ls -l".
|
The stat, fstat and lstat library functions all return information about a file, including the total size in bytes (see the structure definition below); no calculation need take place.
man 2 stat displays the details along with the structure definition: Quote:
Below is a demonstration version, status.c, that can be used to display all the information about one file contained in the stat structure, thus it's not terribly useful for general purposes: Code:
#include <stdio.h> Code:
make status Code:
status file.name Hope this helps some. |
Quote:
(I'm including the inode pointer blocks in what I mean by the inode, even though some of them can be indirect. They're still part of the metadata not part of the file.) ((OK now I think I know what you mean. If the file is sparse (or in some other cases) it may use less disk space - fewer physical disk blocks - than its apparent size. The space used, as reported by du (and the Blocks: part of stat), is the combined size of all the disk blocks it uses ... but this is still recorded in the inode and indirect metadata, not in the "file itself". ls and the Size: part of stat report the actual or apparent size read from a single field in the inode. For most files, this will be a bit smaller than the space used, if the last disk block is not full. But either way these are different meanings, one is not more accurate than the other.)) |
For a pathological case, try
Code:
dd of=takes-no-space bs=1 count=0 seek=100G Code:
ls -1h takes-no-space |
The file actually is taking that space on the drive. That space is reserved and can't be used so I guess we get to the question of what is the size. Size on disk or actual size of file.
|
@jefro: if you're replying to me, no it isn't! It's not taking any space; no disk blocks are reserved.
|
10 terabytes works too. I promise i don't have that much disk.
Code:
$ dd of=takes-no-space bs=1 count=0 seek=10T Code:
dd: failed to truncate to 17592186044416 bytes in output file `takes-no-space': File too large |
Quote:
Code:
char const *size = |
All times are GMT -5. The time now is 09:15 AM. |