【问题标题】:What's wrong with my stat() function in C in linux [duplicate]我在 linux 中的 C 中的 stat() 函数有什么问题 [重复]
【发布时间】:2016-11-30 21:37:17
【问题描述】:

我正在尝试使用 stat() 列出文件信息(包括目录等)

当我将“.”(当前目录)作为 argv[1](例如 $./a.out .)时,它工作正常

但是当我给其他目录如“..”、“/”等时出现错误。

当direntp指向“..”(父目录)后,stat函数返回-1(失败)。

这是一个例子。

$ ls -a ..
. .. sample temple

$ ./a.out ..
Success: .
Success: ..
Fail: sample
Stat Call Error.
Terminate.

$

那么为什么当我给 stat() 的参数提供其他路径时它会失败?

下面是我的代码

#include "stdio.h"
#include "dirent.h"
#include "sys/stat.h"
#include "unistd.h"
#include "stdlib.h"

int main(int argc, char const *argv[])
{
    DIR *dirp;
    struct dirent *direntp;
    struct stat statbuf;

    dirp = opendir(argv[1]);
    while((direntp = readdir(dirp)) != NULL)
    {
        if(direntp->d_ino == 0)
            continue;
        if(direntp->d_name[0] != '.'); /* doesn't matter, This isn't a mistake */
        {
            if(stat(direntp->d_name, &statbuf) == -1)
            {
                printf("Fail: %s\n", direntp->d_name);
                printf("Stat Call Error\n");
                exit(-1);
            }
            printf("Success: %s\n", direntp->d_name);
        }
    }
    closedir(dirp);
    return 0;
}

【问题讨论】:

  • if(stat(direntp->d_name, &statbuf) d_name); : 可以编译吗?
  • 我修复了代码。左括号被省略了,因为它被认为是html中的标签,所以我改为== -1
  • if(direntp->d_name[0] != '.'); 表示该行之后的所有内容都会运行而不考虑direntp->d_name[0] 的值
  • doesn't matter, This isn't a mistake 不,这不是语法错误,但实际上是无操作和完全废话。 (并且您不应该在 stat() 错误时退出,而应继续(例如,由于竞争条件))

标签: c linux stat


【解决方案1】:

opendir 函数使用相对路径返回目录内容,而不是绝对路径。

当您不扫描当前目录时,您只有条目的名称,但没有其完整路径,因此 stat 在所有条目上都失败,因为它在当前目录中查找它们(但 .和.. 也存在于当前目录中)。

当然可以在当前目录下工作,没有这个问题。

修复:组成完整的路径名,例如:

char fp[PATH_MAX];
snprintf(fp, sizeof(fp), "%s/%s", argv[1], direntp->d_name);
if(stat(fp, &statbuf)) {
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多