我正在尝试制作复制程序.它类似于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]);
Run Code Online (Sandbox Code Playgroud)
您只需要读取源文件的权限并在目标文件上设置相同的权限.您可以使用它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);
}
Run Code Online (Sandbox Code Playgroud)
(省略了NB错误检查).
在您main底部的功能中,您可以简单地执行此操作:
chmod(av[2], file1.st_mode);
Run Code Online (Sandbox Code Playgroud)
另一种选择是简单地使用正确的权限创建文件:
代替:
if ( (out_fd=creat( av[2], COPYMODE)) == -1 )
Run Code Online (Sandbox Code Playgroud)
做
if ( (out_fd=creat( av[2], file1.st_mode)) == -1 )
Run Code Online (Sandbox Code Playgroud)