在C语言中,如何知道一个文件是否可被其他用户读取?

在C语言中,如何知道一个文件是否可被其他用户读取?,c,C,我正在使用linux制作一个简单的web服务器。我想知道我应该使用哪些函数来获得文件的可读性。您可以这样尝试: su username -c 'ls /long/dir/user/yourfilename' 或 在上面的示例中,其他人对当前目录中的test.txt文件是否具有读取权限 使用以下宏检查用户、其他人和组的权限 S_IRWXU-所有者的读、写和执行权限 S_IRUSR-所有者具有读取权限 S_IWUSR-所有者具有写入权限 S_IXUSR-所有者具有执行权限 S_IRWXG-组的读、

我正在使用linux制作一个简单的web服务器。我想知道我应该使用哪些函数来获得文件的可读性。

您可以这样尝试:

su username -c 'ls /long/dir/user/yourfilename'

在上面的示例中,其他人对当前目录中的test.txt文件是否具有读取权限

使用以下宏检查用户、其他人和组的权限

S_IRWXU-所有者的读、写和执行权限

S_IRUSR-所有者具有读取权限

S_IWUSR-所有者具有写入权限

S_IXUSR-所有者具有执行权限

S_IRWXG-组的读、写和执行权限

S_IRGRP-组具有读取权限

S_IWGRP-组具有写入权限

S_IXGRP-组具有执行权限

S_IRWXO-其他人的读、写和执行权限

S_IROTH-其他人已获得阅读许可

S_IWOTH-其他人有写权限

S_IXOTH-其他人具有执行权限

使用上述宏根据示例ifbuf.st_mode&S_IROTH中的if条件修改代码。

如果要使用文件描述符而不是路径,则应使用stat函数或fstat

#include <stdio.h>
#include <stdlib.h>  
#include <sys/stat.h>
int main()
{
    char *f = "test.ts";

    struct stat *buff = malloc(sizeof(struct stat));
    if (stat(f,buff) < 0)
    return 1;

    printf("Information for %s\n",f);

    printf("File Permissions: \t");
    printf( (S_ISDIR(buff->st_mode)) ? "d" : "-");
    printf( (buff->st_mode & S_IRUSR) ? "r" : "-");
    printf( (buff->st_mode & S_IWUSR) ? "w" : "-");
    printf( (buff->st_mode & S_IXUSR) ? "x" : "-");
    printf( (buff->st_mode & S_IRGRP) ? "r" : "-");
    printf( (buff->st_mode & S_IWGRP) ? "w" : "-");
    printf( (buff->st_mode & S_IXGRP) ? "x" : "-");
    printf( (buff->st_mode & S_IROTH) ? "r" : "-");
    printf( (buff->st_mode & S_IWOTH) ? "w" : "-");
    printf( (buff->st_mode & S_IXOTH) ? "x\n" : "-\n");

    return 0;
}
使用系统调用?
#include<stdio.h>
#include<sys/stat.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
int i=0;
struct stat buf;
char ptr[]="test.txt";
printf("%s: ",ptr);
if (stat(ptr, &buf) < 0)
{
perror("stat error\n");
return;
}
if(buf.st_mode & S_IROTH)
{
 printf("The Others have a read permission for file %s\n",ptr);
}
 exit(0);
}
#include <stdio.h>
#include <stdlib.h>  
#include <sys/stat.h>
int main()
{
    char *f = "test.ts";

    struct stat *buff = malloc(sizeof(struct stat));
    if (stat(f,buff) < 0)
    return 1;

    printf("Information for %s\n",f);

    printf("File Permissions: \t");
    printf( (S_ISDIR(buff->st_mode)) ? "d" : "-");
    printf( (buff->st_mode & S_IRUSR) ? "r" : "-");
    printf( (buff->st_mode & S_IWUSR) ? "w" : "-");
    printf( (buff->st_mode & S_IXUSR) ? "x" : "-");
    printf( (buff->st_mode & S_IRGRP) ? "r" : "-");
    printf( (buff->st_mode & S_IWGRP) ? "w" : "-");
    printf( (buff->st_mode & S_IXGRP) ? "x" : "-");
    printf( (buff->st_mode & S_IROTH) ? "r" : "-");
    printf( (buff->st_mode & S_IWOTH) ? "w" : "-");
    printf( (buff->st_mode & S_IXOTH) ? "x\n" : "-\n");

    return 0;
}