In: Computer Science
I made the command cp code in c language. But when I copy a file, file permissions are not copied equally. So I want to copy the file authority as well. What should I do?
#include
#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc, char *argv[])
{
struct stat st;
char ch;
int src, dst;
if(argc != 3)
{
printf("argument error \n");
printf("usage: ./a.out src dest \n");
exit(0);
}
src = open(argv[1], O_RDONLY);
if(src == -1){
perror("open source");
exit(errno);
}
dst = open(argv[2], O_WRONLY | O_CREAT|O_TRUNC,
st.st_mode&(S_IRWXU | S_IRWXG | S_IRWXO));
if(dst == -1){
perror("open source");
exit(errno);
}
while(read(src, &ch,1))
write(dst,&ch,1);
close(src);
close(dst);
return 0;
}
file name 1.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#define BUF_SIZE 1024
int main(int argc, char *argv[])
{
struct stat st;
int inputFd, outputFd, openFlags;
ssize_t numRead;
char buf[BUF_SIZE];
if(argc != 3)
{
printf("argument error \n");
printf("usage: ./a.out src dest \n");
exit(0);
}
/*
save the stat structure of the file which you are about to copy
it contains all the information related to file including permission assign
*/
stat(argv[1],&st);
/* Open input and output files */
if((inputFd = open(argv[1], O_RDONLY) )== EACCES)
{
perror("access to the file is not allowed or the file did not exist yet ");
}
else{
printf("file open successfully\n");
}
if((outputFd = open(argv[2], O_CREAT | O_WRONLY,st.st_mode & 511)) < 0)
{
printf("error in opening file %d",errno);
//get error no and search in error list
}
else{
printf("file open successfully\n");
}
/*
O_CREAT flag is use to create file on not exist.
struct stat has member st_mode which contain the file type and file mode.
least significant 9 bits correspond as the file permission bits.
so we perform and operation between st_mode and 511 to reterive permission bits.
*/
/* Transfer data until we encounter end of input or an error */
printf("%d\n",outputFd );
while ((numRead = read(inputFd, buf, BUF_SIZE)) > 0)
{
if(write(outputFd,buf,numRead) <0)
{
printf("error write %d",errno);//get error no. and check error through list of error
}
}
exit(0);
}
compile command
gcc -o 1 1.c
This program is successfully run in ubuntu 20.04.
for error list type below command on linux terminal
errno -l