|
CS456 - Systems Programming
Spring 2023
|
Displaying ./code/h1/copy.c
/*
implementing a version of the "cp" command using Linux System Calls
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
int main(int argc, char **argv){
if(argc < 3){ //prints usage statement to stderr if not enough arguments
//file descriptor 2 is stderr
//string is 41 bytes long
write(2,"Usage: copy source_file destination_file\n", 41);
return 1; //since we're only using system calls, well return 1 to exit the program
}
int src; //declares file descriptor for source file
src = open(argv[1], O_RDONLY); //open the source file specified by user (YOU DO THIS)
//check the return value of open here (YOU DO THIS)
//if it is -1, use write to print a statement to stderr (which file descriptor is that?)
//then return a value of -1 to exit the program
if(src == -1){
write(2, "open failed\n", 12);
return -1;
}
//Using the system call fstat to get the size of the file
int size; //declare size variable
struct stat st; //needed so we can use stat
fstat(src, &st); //accessing the stat struct
size = st.st_size; //getting file size
int dst; //declare a file descriptor for the destination file
dst = open(argv[2], O_CREAT | O_WRONLY | O_TRUNC, 0644); //open the destination file for writing (YOU DO THIS)
//if the file doesn't exist, create it
//if it does exist, truncate it (in other words, we're overwriting the contents)
//also set permissions to 0644
char srcbuf[size+1]; //setting up the buffer to read into
//making buffer size 1 byte larger than file size, just to be safe
// DO THESE TWO THINGS
//use read to read the file contents into the buffer we just set up
//then use write to write whatever is in the buffer we just read into to the destination file
read(src, srcbuf, size);
write(dst, srcbuf, size);
//we're done, so close the file descriptors
close(src);
close(dst);
return 0;
}
|