【问题标题】:Unix: copy a file with original permission in C [duplicate]Unix:在C中复制具有原始权限的文件[重复]
【发布时间】:2017-09-23 10:31:45
【问题描述】:

我正在尝试制作一个复制程序。类似于linux中的cp函数。我可以使用 ./copy file1 file2 成功复制文件,但不知何故,来自源的权限不会复制到目标。有谁知道如何做到这一点?示例和代码如下所示:)

我的文件及其原始权限。

已成功复制文件,但未复制权限。

#define buff_s      4096
#define mod        0644

void printError(char *, char *);

main(int ac, char *txts[])
{
    int     input, output, n_chars;
    char    buf[buff_s];

    struct stat file1;
    struct stat file2;
    stat(txts[1], &file1);
    stat(txts[2], &file2);

    if ( (input=open(txts[1], O_RDONLY)) == -1 )
        printError("error", av[1]);

    if ( (output=creat( txts[2], mod)) == -1 )
        printError( "error", txts[2]);

【问题讨论】:

  • 还要注意read()write() 返回ssize_t 而不是int。它们相同。
  • 感谢您指出这一点。
  • Garg365,我试试你提供的方法,我觉得也可以

标签: c linux unix


【解决方案1】:

您只需要读取源文件的权限并在目标文件上设置相同的权限。您可以使用stat() 读取权限并使用chmod() 进行设置:

#include <sys/stat.h>

void copyPermission(const char* fromFile, const char* toFile) {
    struct stat tmp;
    stat(fromFile, &tmp);
    chmod(toFile, tmp.st_mode);
}

(注意省略错误检查)。

在底部的main 函数中,您只需执行以下操作:

chmod(av[2], file1.st_mode);

另一种选择是简单地创建具有正确权限的文件:

代替:

if ( (out_fd=creat( av[2], COPYMODE)) == -1 )

if ( (out_fd=creat( av[2], file1.st_mode)) == -1 )

【讨论】:

  • 由于文件正在被复制并且进程有打开的文件描述符,您也可以直接在文件描述符上使用fstat()fchmod()
  • 我相信您给我的第二种解决方案是最好的。感谢你们对我的帮助 :)。吸取教训,我从没想过这么简单。
  • Andrew Henle,我会尝试您的方法并尽快更新解决方案。 (如果有效)
猜你喜欢
  • 2012-02-28
  • 2022-01-15
  • 2010-11-26
  • 1970-01-01
  • 2015-08-30
  • 2018-02-14
  • 2013-09-18
  • 2011-08-26
  • 2010-11-07
相关资源
最近更新 更多