help with stat() and fopen()
Code:
/* a very simple copy command for unix */
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <string.h>
int main(int argc, char *argv[])
{
struct stat flinfo; /* structure holding file info read by stat() */
if (argc != 3)
display_usage(1);
/* we're doing a copy, so we want to see the permissions of file a */
errno = 0;
if ( (stat(argv[1], flinfo)) == -1) {
fprintf(stderr, "copy: %s: %s\n", argv[1], strerror(errno));
exit(1);
}
/* open argv[1] for reading */
fd = open(argv[1], O_RDONLY);
/* now open argv[2] with same permissions as argv[1], so that the resulting
copied file has same permissions */
errno = 0;
if ( (fd2 = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, flinfo.st_mode)) == -1)
fprintf(stderr, "copy: %s: %s\n", argv[2], strerro(errno));
exit(1);
}
/* then here I'd do the actual copy with read() and write() */
}
I'm doing the above with low level (OS specific) functions and wish to do them with
fopen, fgetc, etc. My problem is with using the 'mode' argument with fopen() so that the
resulting file will be of the same permissions (executable, etc). The above worked fine
using the above code (plus the rest, not shown) to make a simple 'copy' command. You can
pass the st_mode of the first file you open read with stat(), to open(). Can I do the same
with the fopen() function? I tried fopen() and then did a stat(), and then used umask() to
set the mode of the 2nd file I wanted to create with fopen() for the copy, but it didn't
seem to work. Can anyone give some suggestions?
thanks :)