2011-03-30 52 views
0

复制文件,这里是我的问题之后的权限:在C语言中,我创建了一个文件的副本(含部分变更)这是通过fopen()函数,getchar函数和平凡的putchar完成。 复制该文件是好的,OUTPUTFILE本身是什么,我希望它是。饲养fileowner并用C

我的问题是:我以为我会经常使用该程序的须藤,然后将生成的文件既有另一个所有者(根),以及不同的权限(执行权利都没有了)。

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

回答

2

使用FSTAT(2)系统调用,以获取有关业主的详细资料和权限,以及fchmod(2)和fchown(2)系统调用来设置它们。看到* BSD CPsetfile函数的一个例子(1)source code

+0

...或'fstat(fileno(source))'和'fchown(fileno(dest))',以防止竞争条件。 – 2011-03-30 13:21:44

2

,因为你使用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()'荷兰国际集团