In: Computer Science
This code is an expression of cp command in c language. But I don't understand this code very well. Please explain in notes one by one.(in detail)
#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<errno.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
int main(int argc, char *argv[])
{
char ch;
int src, dst;
struct stat st;
if(argc != 3)
{
printf("argument error \n");
printf("usage: ./a.out src dest \n");
exit(0);
}
if (stat(argv[1], &st) == -1) {
perror("stat : ");
exit(-1);
}
src = open(argv[1], O_RDONLY);
if(src == -1){
perror("open source");
exit(errno);
}
dst = open(argv[2], O_WRONLY | O_CREAT|O_TRUNC);
if(dst == -1){
perror("open source");
exit(errno);
}
while(read(src, &ch,1)){
write(dst,&ch,1);
}
close(src);
close(dst);
if (chmod(argv[2], st.st_mode)) {
perror("chmod : ");
return -1;
}
return 0;
}
i) First check if both source and the destination files are received from the command line argument and exit if argc counter is not equal to 3.
ii) Open the source file with read only flag set.
iii) Open the destination file with the respective flags & modes.
O_WRONLY :Open the file in write only mode
O_TRUNC : Truncates the contents of the existing file
O_CREAT :Creates a new file if it doesn’t exist
iv) Start data transfer from source file to destination file till it reaches EOF ((read(src, &ch,1)==0)
#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<errno.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
int main(int argc, char *argv[])
{
char ch;
int src, dst;
struct stat st;
//Check if both src & dest files are received
if(argc != 3)
{
printf("argument error \n");
printf("usage: ./a.out src dest \n");
exit(0);
}
if (stat(argv[1], &st) == -1) {
perror("stat : ");
exit(-1);
}
//Open source file
src = open(argv[1], O_RDONLY);
if(src == -1){
perror("open source");
exit(errno);
}
//Open destination file with respective flags & modes O_CREAT & O_TRUNC is to truncate existing file
dst = open(argv[2], O_WRONLY | O_CREAT|O_TRUNC);
if(dst == -1){
perror("open source");
exit(errno);
}
//Start data transfer from src file to dst file till it reaches EOF
while(read(src, &ch,1)){
write(dst,&ch,1);
}
close(src);
close(dst);
if (chmod(argv[2], st.st_mode)) {
perror("chmod : ");
return -1;
}
return 0;
}
)