简体   繁体   English

从该设备上文件的名称/描述符获取存储设备块大小

[英]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.). 假设我有一个文件名或一个驻留在存储设备(硬盘,USB闪存,DVD等)上的文本文件的打开文件描述符。 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. 如何在Linux中以编程方式从C中的文件名/描述符中获取该设备的块大小。我知道ioctl系统调用,但是它接受设备专用文件的打开描述符,而不是该设备上文件的打开描述符。

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). 例如,我在某个存储设备(例如/ dev / sda1)上有一个文件名“ /home/hrant/file1.txt”(或该文件上的打开文件描述符)。 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. 如何获取该设备的块大小以块为单位读取文件“ /home/hrant/file1.txt”的内容。

As fstat() man page says: 正如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. stat()函数获取有关路径指向的文件的信息。 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. fstat()获取有关文件描述符fildes已知的打开文件的相同信息。
The buf argument is a pointer to a stat structure as defined by and into which information is placed concerning the file. buf参数是一个指向stat结构的指针,该结构由与文件有关的信息定义并放入其中。 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. 希望对您有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM