Keeping fileowner and permissions after copying file in C

时光总嘲笑我的痴心妄想 提交于 2019-12-02 10:11:16

Use the fstat(2) system call to obtain the details about the owner and the permissions, and the fchmod(2) and fchown(2) system calls to set them. See an example in the setfile function of the *BSD cp(1) source code.

user237419

since you use 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);

as a quick note, you may want to fread() and fwrite() instead of f*char()'ing

Under linux use the libc fchmod and fchown Manpages can be found here:

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!