0

here is my problem: In C, I create the copy of a file (with some changes) This is done trivially via fopen(), getchar and putchar. Copying the file is fine and the outputfile itself is what I want it to be.

My problem is: I assume that I will use this program often as sudo and then the resulting file has both another owner (root) as well as different permissions (execute rights are gone).

My question is: How can I copy the owner and permissions of the original file and then write them into the new one?

Mat
  • 202,337
  • 40
  • 393
  • 406
Chris
  • 2,030
  • 1
  • 16
  • 22

3 Answers3

2

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.

Diomidis Spinellis
  • 18,734
  • 5
  • 61
  • 83
2

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

Lee Netherton
  • 21,347
  • 12
  • 68
  • 102
user237419
  • 8,829
  • 4
  • 31
  • 38
0

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

Angelom
  • 2,413
  • 1
  • 15
  • 8