在 C 程序中检查文件属性

Aym*_*dou 0 c unix

全部,

AFAIK,chmod 函数更改 c 程序中的文件属性。

c 中是否有任何函数可以让您有机会检查(获取)或比较文件属性?

我在程序中想要的是在执行文件之前测试它是否具有适用于 u 和 g(用户和组)的正确 x

Dev*_*lus 6

您正在寻找的是stat,它将返回给定路径的信息。

例子:

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>

#include <sys/types.h>
#include <sys/stat.h>

int main ( int argc, char *argv[])
{
    struct stat FileAttrib;

    if(argc <= 1)
    {
        printf("Argument missing!\n");
        exit(10);
    }

    if (stat(argv[(argc - 1)], &FileAttrib) < 0)
        printf("File Error Message = %s\n", strerror(errno));
    else
        printf( "Permissions: %d\n", FileAttrib.st_mode );

    return 0;
}
Run Code Online (Sandbox Code Playgroud)