|
CS456 - Systems Programming
| Displaying exercises/e1/solution/cp.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#define K 1024
void usage(void)
{
printf("Usage: cp <src> <dst>\n");
exit(0);
}
void help(void)
{
printf("Usage: cp <src> <dst>\n");
printf("Options:\n");
printf(" --help Prints this help\n");
exit(0);
}
int main(int argc, char *argv[])
{
if (argc < 2) usage();
if (argc == 2 && strcmp(argv[1], "--help") == 0) help();
if (argc < 3) usage();
int src = open(argv[1], O_RDONLY);
if (src < 0) {
perror("source open");
exit(1);
}
int dst = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0666);
if (dst < 0) {
perror("destination open");
exit(1);
}
int r;
char buf[K];
while ((r = read(src, buf, K)) > 0) {
if (write(dst, buf, r) < 0) {
perror("write");
exit(1);
}
}
if (r == -1) {
perror("read");
exit(1);
}
close(src);
close(dst);
}
|