【问题标题】:Finding file permission using C使用 C 查找文件权限
【发布时间】:2013-09-03 02:41:48
【问题描述】:

如何使用 C 找到文件的权限?

我正在制作一个文件复制程序,一切正常,只是它不会复制新文件的文件权限。

现在我正在使用 fcntl.h 和 open() 和 creat() 打开文件并制作目标文件,但它正在失去权限。

我希望有一个命令可以将文件权限读取为 0644 或 0777 之类的数字,然后我在 creat() 中使用该数字来制作该文件。有这样的命令吗?

编辑 谢谢大家的帮助,我用下面的代码搞定了

struct stat status;
mode_t permissions;
stat("path_to_file", &status);
permissions = status.st_mode;' 

然后在 creat() 中使用权限;

【问题讨论】:

标签: c file permissions copy posix


【解决方案1】:

使用stat

上面的链接也会为您提供示例代码!

/* Print out type, permissions, and number of links. */
printf("%10.10s", sperm (statbuf.st_mode));
printf("%4d", statbuf.st_nlink);

【讨论】:

    【解决方案2】:

    stat() 函数会得到你需要的东西:http://linux.die.net/man/2/stat

    请注意,您的umask() (http://linux.die.net/man/2/umask) 会影响实际使用的权限。

    【讨论】:

      【解决方案3】:

      here

         struct stat sb;
         mode_t file_permision; // read file permission before copy
      
         if (stat("source_file_name", &sb) == -1) {
              exit(EXIT_FAILURE);
          }
      
       file_permision = sb.st_mode;
      
      //Then create new file
      
       creat("destination_file_name", file_permision );
      

      【讨论】:

      • 谢谢,我使用您的示例使用以下代码。 '结构统计状态; mode_t 权限; stat(argV[i], &status);权限 = status.st_mode;'然后在 creat(); 中使用权限;
      猜你喜欢
      • 2015-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-14
      • 2016-04-14
      • 1970-01-01
      • 2012-09-17
      相关资源
      最近更新 更多