【问题标题】:Get files access permissions using stat() in C在 C 中使用 stat() 获取文件访问权限
【发布时间】:2021-02-26 11:52:28
【问题描述】:

我刚开始学习 linux/C,我只想显示参数中给出的目录的所有文件的名称,以及使用 stat() 的访问权限,这会导致一些问题。 它实际上显示了当前目录中包含的所有文件的正确名称/模式,但是对于参数中给出的其他目录,它确实给出了正确的名称,但所有文件的 st_mode 都相同......

这是我的代码:

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

int main(int argc, char *argv[]) {
    printf("Hello, world!\n");
    int status;
    struct stat sbuf;
    DIR *dirp;
    struct dirent *dp;

    dp = (struct dirent*) malloc(sizeof(struct dirent));


    for (int i=1; i<argc; i++){

        dirp = opendir(argv[i]);
        if (dirp == NULL){/*perror("Argument invalide");*/printf("Argument %d invalid", i); exit(1);}   

        printf("\n\nOpening %s\n", argv[i]);
    do{

        dp = readdir(dirp);

        if (dp != NULL && strcmp(dp->d_name,".") && strcmp(dp->d_name, "..")) { 
            status = stat(dp->d_name,&sbuf);
            printf("The file is %s \tMode :%o\n", dp->d_name, (sbuf.st_mode & 0777));
        }

    } while (dp != NULL);

    closedir(dirp);
    }
    return 0;
}

例如,我确实尝试过: gcc -o test main.c 然后 ./test . ..

结果如下!

Opening .
The file is c.txt   Mode :644
The file is d.txt   Mode :644
The file is xxxx.txt    Mode :777
The file is test    Mode :755


Opening ..
The file is a.txt   Mode :755
The file is b.txt   Mode :755
The file is dossier     Mode :755
The file is main    Mode :755
The file is main.c  Mode :755
The file is test    Mode :755

如您所见,“..”目录下的所有文件都具有相同的模式,这是完全错误的……我确实尝试过使用完整路径和不同的目录,同样的问题。

【问题讨论】:

  • 查看stat的返回值。我想你会发现它失败了。 755 来自上次成功调用 stat。您不能只使用文件名来访问不在当前目录中的文件。
  • 你说得对,我应该添加条件以便在 open()、read()、stat() 有任何问题时返回错误代码。

标签: c linux stat


【解决方案1】:

好吧,stat 没有给你文件信息,因为readdir 给你的是文件名,而不是路径。尝试这样的事情来建立路径,这样你就可以真正调用stat

char *path = malloc(strlen(dp->d_name) + strlen(argv[i]) + 2);
stpcpy(stpcpy(stpcpy(path, argv[i]), "/"), dp->d_name);
status = stat(path,&sbuf);
free(path);

【讨论】:

    猜你喜欢
    • 2010-11-26
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    • 2012-05-06
    • 2019-12-02
    • 2013-12-06
    • 1970-01-01
    相关资源
    最近更新 更多