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.
#define SIZE 1024
#include<string.h>
#include<stdio.h>
#include<sys/types.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/stat.h>
int main(int argc, char *argv[]){
if(argc != 3){
perror("argument 부족\n");
exit(0);
}
struct stat frstatbuf;
FILE* fr = fopen(argv[1], "r");
if(fr == NULL){
perror("read file 읽기 오류\n");
exit(0);
}
int frfd = fileno(fr);
fstat(frfd, &frstatbuf);
FILE* fw=fopen(argv[2], "w+");
int fwfd=fileno(fw);
fchmod(fwfd,frstatbuf.st_mode&(S_IRWXU|S_IRWXG|S_IRWXO));
char buf[1024];
while(1){
int n=fread(buf,sizeof(char),SIZE,fr);
if(n<SIZE){
fwrite(buf,sizeof(char),n,fw);
printf("파일을 다 읽었음\n");
exit(0);
}
fwrite(buf,sizeof(char),n,fw);
}
fclose(fr);
fclose(fw);
return 0;
}
#define SIZE 1024
#include<string.h>
#include<stdio.h>
#include<sys/types.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/stat.h>
int main(int argc, char *argv[]) {
// validate command line arguments.
if(argc != 3){
perror("argument
부족\n");
exit(0);
}
struct stat frstatbuf;
// Open the file and get a file
pointer
FILE* fr = fopen(argv[1], "r");
if(fr == NULL){
perror("read file
읽기 오류\n");
exit(0);
}
// Get file descriptor from file
pointer
int frfd = fileno(fr);
// Read file related information into file
status buffer: frstatbuf
fstat(frfd, &frstatbuf);
// Open a new file for writing
FILE* fw=fopen(argv[2], "w+");
// get file descriptor for file to
write
int fwfd=fileno(fw);
// Change the file permissio of writing
file
// Give read write execute permission to
group, owner and others.
fchmod(fwfd, frstatbuf.st_mode &
(S_IRWXU|S_IRWXG|S_IRWXO));
// buffer to read file contents.
char buf[1024];
while(1){
// try reading SIZE
bytes maximum from file with descriptor fr
// (from input
file)
// The return value
is the number of bytes read successfully
int
n=fread(buf,sizeof(char),SIZE,fr);
// If we are unable
to read all the required number of bytes
// then it is a
errror
if(n <
SIZE){
fwrite(buf,sizeof(char),n,fw);
printf("파일을
다 읽었음\n");
//
end the program here after printing the error.
exit(0);
}
// Else, everything
was fine, we were able to read the data from file
// Now, write the
same number of bytes to output file with descriptor fw.
fwrite(buf,sizeof(char),n,fw);
}
// at last close all the resources
fclose(fr);
fclose(fw);
return 0;
}
**************************************************
please see inline comments.
I have tried to answer your question to best of my efforts.
However, if you still face any issues in the answer, please let me
know via the comment section. Your feedback will imporve as well as
encourage me to keep up the good work.
If i was able to help you, then please provide me an
upvote(thumbs up). Thanks!