#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#define BUFSIZE 1024
static const char *filename = "concat.txt";
int main(int argc, char *argv[])
{
char buf[BUFSIZE] = { 0, };
int i, n;
int fd = -1; /* 読み込み用 */
int concat_fd = -1; /* 書き込み用 */
if (argc < 2) {
printf("Usage: catfiles FILE [FILE]...\n");
exit(1);
}
if ((concat_fd = open(filename, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR)) < 0) {
fprintf(stderr, "failed to open %s: %s\n", filename, strerror(errno));
exit(2);
}
for (i = 1; i < argc; i++) {
if ((fd = open(argv[i], O_RDONLY)) < 0) {
fprintf(stderr, "failed to open %s: %s\n", argv[i], strerror(errno));
continue;
}
for (;;) {
n = read(fd, buf, BUFSIZE);
if (n == 0) {
break;
}
else if (n < 0) {
fprintf(stderr, "failed to read %s: %s\n", argv[i], strerror(errno));
break;
}
else {
if (write(concat_fd, buf, n) != n) {
fprintf(stderr, "failed to write: %s\n", strerror(errno));
close(fd);
close(concat_fd);
exit(3);
}
}
}
close(fd);
}
close(concat_fd);
return 0;
}