C 奇怪的 stat st_mode [英] C strange stat st_mode

查看:21
本文介绍了C 奇怪的 stat st_mode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将 S_ISDIR(info->st_mode)S_ISREG(info->st_mode) 的结果打印在包含带有 .so 扩展,结果很意外,S_ISREG 返回 0S_ISDIR 返回 1.

I am printing the result of S_ISDIR(info->st_mode) and S_ISREG(info->st_mode) over a directory that contains dynamic libraries with .so extension and the result is quite surprising, S_ISREG returns 0 while S_ISDIR returns 1.

我有点糊涂了...

代码:

DIR *dir;
if ((dir = opendir (dirname)) != NULL) {
  struct dirent *ent;
  while ((ent = readdir (dir)) != NULL) {
    struct stat info;
    stat(ent->d_name, &info);
    printf("file: %s, S_ISREG: %d, S_ISDIR: %d", ent->d_name, S_ISREG(info.st_mode), S_ISDIR(info.st_mode));
  }
}
closedir(dir);

输出如下:

file: ., S_ISREG: 0, S_ISDIR: 1
file: zyva.so, S_ISREG: 0, S_ISDIR: 1
file: .gitignore, S_ISREG: 1, S_ISDIR: 0
file: .., S_ISREG: 0, S_ISDIR: 1
file: plugin-app, S_ISREG: 0, S_ISDIR: 1
file: chat.so, S_ISREG: 0, S_ISDIR: 1

plugin-app 也是一个可执行文件,所以它也是一个普通文件...

plugin-app is also an executable so it's also a regular file...

推荐答案

您没有检查 stat() 的返回值.我敢打赌,如果你这样做,你会发现它失败了.在这种情况下,struct stat 没有被填充,所以它只包含未初始化的垃圾(或先前成功调用的结果).

You didn't check the return value of stat(). I'll bet if you do so, you find that it failed. In that case, the struct stat is not filled in, so it just contains uninitialized garbage (or the result of a previous successful call).

为什么会失败?我敢打赌你会发现 errno == ENOENT.注意ent->d_name只包含文件的name,而不是path,所以当你尝试stat 它,它被解释为相对于当前工作目录的路径.除非 dirname 是您已经在的目录,否则您会让 stat 在错误的位置查找这些文件,因此找不到它们也就不足为奇了.

Why did it fail? I bet you find that errno == ENOENT. Note that ent->d_name only contains the name of the file, not the path, so when you try to stat it, it's interpreted as a path relative to the current working directory. Unless dirname is the directory you're already in, you're having stat look for these files in the wrong place, so it's no wonder they aren't found.

要么在执行 stat 之前使用 chdir(dirname),要么在单独的缓冲区中通过在 dirname/ 前面添加完整路径来构建完整路径文件名(确保检查长度以确保不会溢出缓冲区).

Either chdir(dirname) before doing your stats, or else construct the full path in a separate buffer by prepending dirname/ to the filename (make sure to check the lengths to ensure that you do not overrun your buffer).

这篇关于C 奇怪的 stat st_mode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆