Results 1 to 3 of 3
Hi all, i need to find out how many blocks a file is being allocated (in actual) in a c program. I tried this code:
Code:
lstat(filepath, &info) ;
printf("block ...
- 06-02-2011 #1Just Joined!
- Join Date
- Dec 2009
- Location
- Rajshahi || Dhaka, Bangladesh
- Posts
- 11
Disk Block Size in a C program
Hi all, i need to find out how many blocks a file is being allocated (in actual) in a c program. I tried this code:
Which gives me 4096, but the command sfdisk -l gives 1024 which seems to agree with ls -lsi command and therefore correct. So the question is how do i get the actual (correct)block size in a c program ?? Plz help. Thanx in advance.Code:lstat(filepath, &info) ; printf("block size = %d\n", (int)(info.st_blksize)) ;
- 06-03-2011 #2
I think you would need understand the difference between two sizes in stat -
blksize_t st_blksize; /* blocksize for file system I/O */
blkcnt_t st_blocks; /* number of 512B blocks allocated */
What you have retrieved is st_blksize which is nothing but your File System block size. (by default its 4096 or 4KB)
For example, see below file bit.c its size is just 146 bytes
But using stat command you can see$ ls -ltr bit.c
-rw-rw-r--. 1 laks laks 146 2011-05-30 23:16 bit.c
Its says Blocks : 8 and IO Block as 4096[laks@space ~]$ stat bit.c
File: `bit.c'
Size: 146 Blocks: 8 IO Block: 4096 regular file
Device: fd00h/64768d Inode: 249733 Links: 1
Access: (0664/-rw-rw-r--) Uid: ( 500/ laks) Gid: ( 500/ laks)
Access: 2011-05-30 23:16:06.157773774 +0530
Modify: 2011-05-30 23:16:04.844524535 +0530
Change: 2011-05-30 23:16:04.972521528 +0530
Blocks = IO block / 512
which is
Blocks = 4096 / 512 = 8
If I'm not wrong - I think Blocks=8 ( st_blocks ) is rarely used .
So now
its, i need to find out how many blocks a file is being allocated
if (st_size < 4096 )
then actually used blocks = 1
else
blocks = st_size / st_blksize
Btw,Whats your File system? If it belongs to ext family (ext2/ext3/ext4) and you want to dig deeper into them, try using ext2fs libraries.
If you are looking for file's data block then you should be looking at i_block[14] in inode structureLast edited by Lakshmipathi; 06-03-2011 at 08:16 AM.
- Lakshmipathi.G
-------------------
FOSS India Award winning ext3fs Undelete tool and tutorials www.giis.co.in
First they criticize you,Then they laugh at you,Then they fight with you,Then you win. - M.K.Gandhi
-------------------
- 06-03-2011 #3Just Joined!
- Join Date
- Dec 2009
- Location
- Rajshahi || Dhaka, Bangladesh
- Posts
- 11
@Lakshmipathi Thank u a lot, i think i need to look at the inode structure, as i am implementing ls which needs to show the no of blocks occupied by a file when -s flag is given. Yhank u again. very helpful.


Reply With Quote
