Skip to content

Get storage device block size from name/descriptor of a file on that device

Suppose that I have file name or an open file decriptor for a text file that resides on a storage device (hard disk, usb flash, dvd, etc.). How can I get block size of that device from file name/descriptor in Linux programmatically in C. I know about ioctl system call, but it accepts an open descriptor for device special file, not an open descriptor of a file on that device.

For example I have a file name “/home/hrant/file1.txt” (or an open file descriptor on that file) that is on some storage device (like /dev/sda1). I don’t know on which device the file is. How to get block size of that device to read contents of file “/home/hrant/file1.txt” in blocks.



As fstat() man page says:

 int fstat(int fildes, struct stat *buf);  
 int stat(const char *path, struct stat *buf);  

The stat() function obtains information about the file pointed to by path. Read, write or execute permission of the named file is not required, but all directories listed in the path name leading to the file must be searchable.
The fstat() obtains the same information about an open file known by the file descriptor fildes.
The buf argument is a pointer to a stat structure as defined by and into which information is placed concerning the file. the stat structure is defined as:

struct stat {
    dev_t    st_dev;    /* device inode resides on */
    ino_t    st_ino;    /* inode's number */
    mode_t   st_mode;   /* inode protection mode */
    nlink_t  st_nlink;  /* number of hard links to the file */
    uid_t    st_uid;    /* user-id of owner */
    gid_t    st_gid;    /* group-id of owner */
    dev_t    st_rdev;   /* device type, for special file inode */
    struct timespec st_atimespec;  /* time of last access */
    struct timespec st_mtimespec;  /* time of last data modification */
    struct timespec st_ctimespec;  /* time of last file status change */
    off_t    st_size;   /* file size, in bytes */
    quad_t   st_blocks; /* blocks allocated for file */
    u_long   st_blksize;/* optimal file sys I/O ops blocksize */

I hope it helps you.

User contributions licensed under: CC BY-SA
1 People found this is helpful