0

I have to create a program that will create new one or overwrite existing(outfile) file, with the content of an already existing file(infile). For me, this is easy, I've already done this. But my problem is, that outfile needs to have same permission as infile and I have no idea how to do this.

programName infile outfile

My code looks like this, I think that I need to use stat() or fstat() but I'm not really sure how.

#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>

int main(int argc, char** argv) {

    char* infile = argv[1];
    char* outfile = argv[2];

    int in = open(infile, O_RDONLY, S_IRUSR);
    int out = open(outfile, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
    long len = lseek(in, 0L, SEEK_END);
    char buf[len];
    lseek(in, 0L, SEEK_SET);
    read(in, &buf, len);
    write(out, &buf, len);
    close(in);
    close(out);
    return 0;
}

I know that right now I've set permission manually.

BlackWolf
  • 16
  • 6
  • 3
    Use `stat()` to read the permissions from the source file and `chown()/chmod()` to set them on the target file. – Ctx Oct 21 '19 at 15:09
  • 1
    Given you already have open file descriptors, you can use `fstat()`, `fchown()`, and `fchmod()`. That also has the advantage of avoiding possible race conditions. – Andrew Henle Oct 21 '19 at 16:47
  • Possible duplicate of [Keeping fileowner and permissions after copying file in C](https://stackoverflow.com/questions/5486774/keeping-fileowner-and-permissions-after-copying-file-in-c) – LegendofPedro Oct 21 '19 at 17:58

0 Answers0