如何在linux上使用c++为特定文件设置文件属性(1644)

how to set file attributes(1644) to a particular file using c++ on linux

本文关键字:文件 置文件属性 1644 linux c++      更新时间:2023-10-16

我想在linux中使用c++创建一个具有特定文件权限(1644)的文件。我知道我可以用chmod实现这一点,但我想通过c++编程地做到这一点。

这可能吗?请帮助。

谢谢。

使用stat(2)获取权限,然后使用chmod(2)更改权限

更一般地说,要了解某些(命令行)程序(例如/bin/chmod…)执行的系统调用,请使用strace(1)....

你需要在sys/stat.h中使用struct stat

man 2 stat查看各种st_mode字段值

可以使用sys/stat.h中的chmod函数:

int chmod(const char *path, mode_t mode);

比如:

#include <sys/stat.h>
...
if (!chmod("/tmp/testfile",
        S_ISVTX |   // Sticky bit
        S_IRUSR | // User read
        S_IWUSR | // User write
        S_IRGRP | // Group read
        S_IROTH   // Other read
        ))
{
    // Handle error case
}