2011-03-30 76 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()'荷蘭國際集團