How do I list a file's data blocks on Linux?

Solution 1:

You could use the "debugfs" tool to view file info on the command line or interactivley. either use:

# debugfs /dev/<spartition>
# stat /path/to/file

or

# debugfs -R "stat /path/to/file" /dev/<partition>

for example:

# debugfs -R "stat /etc/passwd"  /dev/sda5
Inode: 435914   Type: regular    Mode:  0644   Flags: 0x0
Generation: 979004472    Version: 0x00000000
User:     0   Group:     0   Size: 1577
File ACL: 0    Directory ACL: 0
Links: 1   Blockcount: 8
Fragment:  Address: 0    Number: 0    Size: 0
ctime: 0x4a2d6f78 -- Mon Jun  8 23:07:20 2009
atime: 0x4a2d6f79 -- Mon Jun  8 23:07:21 2009
mtime: 0x4a2d6f78 -- Mon Jun  8 23:07:20 2009
Size of extra inode fields: 4
BLOCKS:
(0):1767438
TOTAL: 1

Solution 2:

Look at the syntax for "debugfs", and specifically the "stat" command. That will show you a list of the data blocks used by a file. You can pass parameters to "debugfs" with the "-f" argument to call it from a script.


Solution 3:

A simple way to get the list of blocks (without having to read from the partition like in the debugfs answers) is to use the FIBMAP ioctl. I do not know of any command to do so, but it is very simple to write one; a quick Google search gave me an example of FIBMAP use, which does exactly what you want. One advantage is that it will work on any filesystem which supports the bmap operation, not just ext3.

A newer (and more efficient) alternative is the FIEMAP ioctl, which can also return detailed information about extents (useful for ext4).


Solution 4:

hdparm --fibmap /path/to/filename

I will not work on zfs, but will on ext4, btrfs, (v)fat, etc

man 8 hdparm :

--fibmap When used, this must be the only flag given. It requires a file path as a parameter, and will print out a list of the device extents (sector ranges) occupied by that file on disk. Sector numbers are given as absolute LBA numbers, referenced from sector 0 of the physical device (not the partition or filesystem). This information can then be used for a variety of purposes, such as examining the degree of fragmenation of larger files, or determining appropriate sectors to deliberately corrupt during fault-injection testing procedures.