#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/uio.h>
#include <unistd.h>
#define INFILE "input.file"
#define OUTFILE "output.file"
enum {
BUFSIZE = 4,
};
int main(void) {
int ifd, ofd;
ssize_t cc;
char buf[BUFSIZE];
if ((ifd = open(INFILE, O_RDONLY)) == -1) {
perror("open input file");
exit(1);
}
if ((ofd = open(OUTFILE, O_WRONLY|O_CREAT|O_TRUNC, 0666)) == -1) {
perror("open output file");
exit(1);
}
while ((cc = read(ifd, buf, sizeof(buf))) > 0) {
if (write(ofd, buf, cc) == -1) {
perror("write");
exit(1);
}
}
if (cc == -1) {
perror("read");
exit(1);
}
if (close(ofd) == -1) {
perror("close output file");
exit(1);
}
if (close(ifd) == -1) {
perror("close input file");
exit(1);
}
return 0;
}
$ cat input.file
abcdef
$ od -tx1 input.file
0000000 61 62 63 64 65 66 0a
GDBによるデバッグ
(gdb) b main
(gdb) r
21 if ((ifd = open(INFILE, O_RDONLY)) == -1) {
(gdb) n
26 if ((ofd = open(OUTFILE, O_WRONLY|O_CREAT|O_TRUNC, 0666)) == -1) {
(gdb) p ifd
$1 = 3
(gdb) n
31 while ((cc = read(ifd, buf, sizeof(buf))) > 0) {
(gdb) p ofd
$2 = 4
(gdb) n
32 if (write(ofd, buf, cc) == -1) {
(gdb) p buf
$3 = "abcd"
(gdb) p cc
$4 = 4
(gdb) n
31 while ((cc = read(ifd, buf, sizeof(buf))) > 0) {
(gdb) n
32 if (write(ofd, buf, cc) == -1) {
(gdb) p buf
$5 = "ef\nd"
(gdb) p cc
$6 = 3
(gdb) n
31 while ((cc = read(ifd, buf, sizeof(buf))) > 0) {
(gdb) n
38 if (cc == -1) {
(gdb) p buf
$7 = "ef\nd"
(gdb) p cc
$8 = 0