在 C 中使用 stat() 获取文件访问权限

问题描述

我刚开始学习 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 没有为您提供文件信息,因为 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);