ch8-cp (Copy files)
Chapter_8 getchar | Exercise_8-1 |
cp.c K&R, p. 173-174 download
#include <stdio.h> // for BUFSIZ, fprintf(), vfprintf(), stderr
#include <stdlib.h> // for exit()
#include <fcntl.h> // for open(), creat(), O_RDONLY
#include <unistd.h> // for read(), write(), fd 0 (stdin), 1 (stdout)
#define PERM 0666 // RW for owner, group, others
void error(char *, ...);
int main(int argc, char *argv[]) // copy file1 to file2
{
char buf[BUFSIZ]; // 8192 bytes
int f1, f2, n;
if (argc != 3)
{error("Usage: %s from to", argv[0]);}
if ((f1 = open(argv[1], O_RDONLY, 0)) == -1) // 0 - permissions
{error("%s: can't open \"%s\"", argv[0], argv[1]);}
if ((f2 = creat(argv[2], PERM)) == -1)
{error("%s: can't create \"%s\", mode %03o", argv[0], argv[2], PERM);}
while ((n = read(f1, buf, BUFSIZ)) > 0)
if (write(f2, buf, n) != n)
{error("%s: write error on file \"%s\"", argv[0], argv[2]);}
close(f1), close(f2);
return 0;
}
#include <stdarg.h> // for va_list, va_start, va_end
// print an error message and die (end program)
void error(char *fmt, ...)
{
va_list args;
va_start(args, fmt);
fprintf(stderr, "Error: ");
vfprintf(stderr, fmt, args);
fprintf(stderr, "\n");
va_end(args);
exit(1); // end program from outside main()
}
/*
gcc cp.c -o cp
./cp
Error: Usage: ./cp from to
./cp stdin stdout
Error: ./cp: can't open "stdin"
./cp 0 1
Error: ./cp: can't open "0"
./cp cp.c cp2.c
diff -s cp.c cp2.c
// Files cp.c and cp2.c are identical
meld cp.c cp2.c
// Files are identical
rm cp2.c // clean
*/
Chapter_8 getchar | BACK_TO_TOP | Exercise_8-1 |
Comments
Post a Comment