stat() 是如何工作的?
stattest.c:
// compile: gcc -o stattest stattest.c
#include <stdio.h>
#include <sys/stat.h>
int main(int argc, char *argv[]) {
struct stat stats;
stat(argv[1], &stats);
printf("%lli\n", (long long)stats.st_dev);
return 0;
}
用法:
stat -f "%r" /dev/disk0 => 234881024 (Value that I'm looking for.) ./teststat /dev/disk0 => 44921876 python -c 'import os,sys; print os.stat(sys.argv[1]).st_dev' /dev/disk0 => 44921876
为什么我的代码没有给我 stat 命令给我的值?
更新 1
提取主编号 44921876 得到 2,即 /dev/tty
。
更新 2
在文件系统上指定文件是有效的。 (我在这里只使用 python,因为它更快。)
python -c "import sys,os; print os.stat(sys.argv[1]).st_dev" /path/to/file => 234881024
stattest.c:
// compile: gcc -o stattest stattest.c
#include <stdio.h>
#include <sys/stat.h>
int main(int argc, char *argv[]) {
struct stat stats;
stat(argv[1], &stats);
printf("%lli\n", (long long)stats.st_dev);
return 0;
}
Usage:
stat -f "%r" /dev/disk0 => 234881024 (Value that I'm looking for.) ./teststat /dev/disk0 => 44921876 python -c 'import os,sys; print os.stat(sys.argv[1]).st_dev' /dev/disk0 => 44921876
Why doesn't my code give me the value the stat
command gives me?
Update 1
Extracting the major number of 44921876 gives me 2 which is /dev/tty
.
Update 2
Specifying a file on the filesystem works. (I'm only using python here because it's faster.)
python -c "import sys,os; print os.stat(sys.argv[1]).st_dev" /path/to/file => 234881024
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试打印
st_rdev
成员。手册页说:我认为您没有打印 %r 格式化程序访问的同一字段。您对设备文件所在的设备不感兴趣,而是对文件描述的设备感兴趣。
这些数字至少与您的 ls 输出一致; Major=14 且 Minor=0,则打印 234881024,其十六进制为 0xE000000。 0xE 当然是十进制的 14。这表明 Mac OS X 将主编号存储在前 8 位中,将次编号存储在低 24 位中。这又意味着
dev_t
类型是 32 位,这使得您的打印它的long long
有点可疑。Try printing the
st_rdev
member. The manual page says:I think you're not printing the same field that the %r formatter accesses. You're not interested in the device the device file is on, but the device that the file describes.
The numbers are at least consistent with your
ls
output; major=14 and minor=0, and you print 234881024, which in hex is 0xE000000. 0xE is, of course, 14 decimal. This indicates Mac OS X stores the major number in the top 8 bits, and the minor number in the lower 24. This, in turn, implies that thedev_t
type is 32-bit, which makes your printing it aslong long
a bit dubious.