从该设备上的文件的 name/descriptor 获取存储设备块大小

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

假设我有驻留在存储设备(硬盘、USB 闪存、DVD 等)上的文本文件的文件名或打开文件描述符。如何在 C 中以编程方式从 Linux 中的文件 name/descriptor 中获取该设备的块大小。我知道 ioctl 系统调用,但它接受设备特殊文件的打开描述符,而不是设备特殊文件的打开描述符该设备上的文件。

例如,我在某些存储设备(如 /dev/sda1)上有一个文件名“/home/hrant/file1.txt”(或该文件的打开文件描述符)。我不知道文件在哪个设备上。如何获取该设备的块大小以块为单位读取文件“/home/hrant/file1.txt”的内容。

fstat() 手册页所述:

 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 */
 };

希望对你有所帮助