Linux Get physical location from file and write contents

276 Views Asked by At

I want to get the physical location of linux file, /root/f.txt and write(overwrite) some contents of file

  1. File is /root/f.txt
  2. lsblk command output:
# lsblk
NAME          MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
fd0             2:0    1    4K  0 disk
sda             8:0    0   16G  0 disk
├─sda1          8:1    0    1G  0 part /boot
└─sda2          8:2    0   15G  0 part
  ├─rhel-root 253:0    0 13.4G  0 lvm  /
  └─rhel-swap 253:1    0  1.6G  0 lvm  [SWAP]
sdb             8:16   0    1G  0 disk
sr0            11:0    1 1024M  0 rom

Contents of file:

#cat /root/f.txt
This is new file ha ha ha
  1. From 'filefrag' command I get pysical location of file
#filefrag -v /root/f.txt
Filesystem type is: 58465342
File size of /root/f.txt is 26 (1 block of 4096 bytes)
ext:     logical_offset:        physical_offset: length:   expected: flags:
 0:        0..       0:    1761827..   1761827:      1:             eof
/root/f.txt: 1 extent found
  1. Here physical block starts at 1761827 and 1 block is of 4096. So physical location of file would be: 1761827 * 4096 = 7216443392

  2. I have only '/dev/sda' and I am trying to write at location 7216443392 with dd command as:

#sudo dd seek=7216443392 if=/dev/zero of=/dev/sda count=1 obs=1
1+0 records in
512+0 records out
512 bytes (512 B) copied, 0.00699863 s, 73.2 kB/s
  1. But when I saw contents of file /root/f.txt, output is still same
 #cat /root/f.txt
 This is new file ha ha ha

So either the physical location is not correct, or I do something wrong with dd. Please suggest.

1

There are 1 best solutions below

0
On

The initial cat pulls the file into the page cache. Then, you directly write to the block device using dd. At this point, the kernel has no reason to believe the page in memory is not consistent with disk, so the new contents you write to the block device are not reflected when you cat after dd.

To see the new data written using dd, sync(1) and drop the page cache before running dd:

sync
sudo sh -c 'echo 1 > /proc/sys/vm/drop_caches'