c++ - 无需 super 用户即可更改文件权限

标签 c++ c linux

我想在目录中读取一些来自第三方工具的文件。在读取这些文件之前,我会检查它们是否是常规文件

阅读之前

if (!S_ISREG(file_info.st_mode))
{
    return false;
}

读完这个文件后,我想更改它的权限,这样它就不会被一次又一次地读取。

我的问题是如何更改文件权限 st_mode 以便我的应用程序在不是 super 用户的情况下不会再次读取它。

我的 Linux 发行版是 RedHat

最佳答案

如果你读了一个文件,不想再读一遍,你不应该测试它是否是一个普通文件,因为不管它有什么权限,一个普通文件就是一个普通文件。所以我认为你应该检查读取权限,如果设置了,读取文件,并使用 chmod() 设置权限以禁止读取。

/* Check it it is readable by the user */
if ((file_info.st_mode & S_IRUSR)==0)
{
  return false;
}

/* If it is, open and read the file... */
...
...

/* Mark it as not readable by the user. file_name is assumed
   to be the name of the file as you have used it upon calling
   lstat */
chmod (file_name, file_info.st_mode & ~S_IRUSR);

关于c++ - 无需 super 用户即可更改文件权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20123072/

相关文章:

c - 在片段着色器 cg/Unity 中照亮模型(立方体、球体……)

linux - 在 Linux 中使用 C 将一个文件的精确统计参数应用到另一个文件

linux - Linux 中的粒子可视化

c - 函数属性 noclone 的用途

c - 从进程中取消绑定(bind)击键

C++将一个数组拆分为2个单独的数组

c++ - 将标准输出重定向到文件

linux - 搜索文件夹中的所有子文件夹时,得到 "[: if-then: unexpected operator "

c++ - 冒泡排序 : Why it isn't working correctly?

c++ - C++ 中指向自身内部类的指针