【问题标题】:Get storage device block size from name/descriptor of a file on that device从该设备上文件的名称/描述符获取存储设备块大小
【发布时间】:2015-04-22 05:17:31
【问题描述】:
假设我有一个驻留在存储设备(硬盘、USB 闪存、DVD 等)上的文本文件的文件名或打开的文件描述符。如何在 C 中以编程方式从 Linux 中的文件名/描述符获取该设备的块大小。我知道 ioctl 系统调用,但它接受设备特殊文件的打开描述符,而不是该设备上文件的打开描述符。
例如,我在某个存储设备(如 /dev/sda1)上有一个文件名“/home/hrant/file1.txt”(或该文件上的打开文件描述符)。我不知道文件在哪个设备上。如何获取该设备的块大小以读取块中文件“/home/hrant/file1.txt”的内容。
【问题讨论】:
标签:
c
linux
file-descriptor
【解决方案1】:
正如fstat() 手册页所说:
int fstat(int fildes, struct stat *buf);
int stat(const char *path, struct stat *buf);
stat() 函数获取有关路径指向的文件的信息。指定文件的读、写或执行权限不是必需的,但指向该文件的路径名中列出的所有目录都必须是可搜索的。
fstat() 获取有关文件描述符 fildes 已知的打开文件的相同信息。
buf 参数是一个指向 stat 结构的指针,该结构由文件定义,并在其中放置有关文件的信息。
stat结构定义为:
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 */
};
希望对你有帮助。