|
CS456 - Systems Programming
Spring 2026
|
Displaying ./code/h2/copyim.c
/*
we start with a simple implementation of the copy command, and are going to make
a couple improvements.
i've included below a header file i made myself called "extras.h" that currently
has two functions:
get_fdSize - takes a file descriptor, returns the size of the file
int get_fdSize(int fd);
get_fdPerms - takes a file descriptor, returns the file permissions
int get_fdPerms(int fd);
You will use these two functions to make the following improvements:
1. Currently, this is hardcoded to read up to 1024 bytes, change this so that it
will read whatever the size of the file is
2. The pemissions of the target file are hardcoded to 0666 (read-write for
everyone) change this so that the target file has the same permissions as the
source file.
Use the functions I provided to accomplish this.
> gcc -o copyim copyim.c
> ./copyim src dst
*/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
//including my own header file here
#include "extras.h"
int main(int argc, char **argv){
//prints usage statement if required arguments are unavailable
if(argc < 3){
fprintf(stderr, "Usage: %s source target\n", argv[0]);
exit(1);
}
//declares file descriptor and opens source file for reading
int src = open(argv[1], O_RDONLY);
//check return value for errors
if(src == -1){
fprintf(stderr, "Error in file %s: ", argv[1]);
perror("open");
exit(-1);
}
//creating arrays for buffer
char buffer[1024];
//declare file descriptor and open target for writing
int dst = open(argv[2], O_WRONLY | O_TRUNC | O_CREAT, 0666);
int data = read(src, buffer, 1024);
write(dst, buffer, data);
close(src);
close(dst);
return 0;
}
|