c - Unix:在C中复制具有原始权限的文件

标签 c linux unix

<分区>

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

我的文件及其原始权限。 My files and their original permission.

成功复制文件但未复制权限。 Successfully copied the file but the permission was not copied.

#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]);

最佳答案

您只需要读取源文件的权限并在目标文件上设置相同的权限即可。您可以使用 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 )

关于c - Unix:在C中复制具有原始权限的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43627117/

相关文章:

shell - 'export'命令有什么作用?

使用 strcmp() 函数时逻辑困惑

C sprintf - 您能解释一下以下内容吗?

c - C语言strtok有一些错误

linux - 设置 bash shell 或命令提示符以运行 Python 项目

c++ - 如何在 C++11 中将 Unix 时间戳字符串转换为 time_t?

c - 十六进制无法在自制的 printf() 函数中正确打印

Linux 退出命令什么都不做

linux - PowerPC Linux 上的 D(和 Tango)

linux - 下面的 UNIX 代码的输出是什么?