【问题标题】:Keeping fileowner and permissions after copying file in C在 C 中复制文件后保留文件所有者和权限
【发布时间】:2011-07-26 02:22:35
【问题描述】:

这是我的问题:在 C 中,我创建了一个文件的副本(进行了一些更改) 这可以通过 fopen()、getchar 和 putchar 轻松完成。 复制文件很好,输出文件本身就是我想要的。

我的问题是:我假设我会经常将这个程序用作 sudo,然后生成的文件既有另一个所有者(root)又有不同的权限(执行权限消失了)。

我的问题是:如何复制原始文件的所有者和权限,然后将它们写入新文件?

【问题讨论】:

    标签: c permissions file-ownership


    【解决方案1】:

    因为你使用 fopen():

    #include <sys/types.h>
    #include <sys/stat.h>
    #include <unistd.h>
    
    //fp is your source filepointer, fdest is your dest filepointer
    //fn is the  new filename you're copying to
    
    struct stat fst;
    //let's say this wont fail since you already worked OK on that fp
    fstat(fileno(fp),&fst);
    //update to the same uid/gid
    fchown(fileno(fdest),fst.st_uid,fst.st_gid);
    //update the permissions 
    fchmod(fileno(fdest),fst.st_mode);
    

    作为一个简短的说明,您可能想要 fread() 和 fwrite() 而不是 f*char()'ing

    【讨论】:

      【解决方案2】:

      使用fstat(2) 系统调用获取有关所有者和权限的详细信息,以及fchmod(2) 和fchown(2) 系统调用来设置它们。请参阅 *BSD cp(1) source codesetfile 函数中的示例。

      【讨论】:

      • ... 或 fstat(fileno(source))fchown(fileno(dest)),以防止出现竞争情况。
      【解决方案3】:

      在 linux 下使用 libc fchmod 和 fchown 手册页可以在这里找到:

      http://linux.die.net/man/2/fchmod

      http://linux.die.net/man/2/fchown

      【讨论】:

        猜你喜欢
        • 2013-11-16
        • 2018-02-27
        • 2012-04-17
        • 2013-10-08
        • 2017-04-24
        • 1970-01-01
        • 2014-02-04
        • 2012-01-10
        • 1970-01-01
        相关资源
        最近更新 更多