#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
int main(int argc, char *argv[])
{
long count;
int source, target, ch;
char *buf;
struct stat filestat;
if(argc < 3) {
printf("***error use: test file1 file2\n");
exit(1);
}
/*
ファイルのオープン
*/
if((source = open(argv[1], O_BINARY|O_RDONLY)) == -1) {
printf("***error ファイル %s をオープンできません\n", argv[1]);
exit(1);
}
target = open(argv[2], O_BINARY|O_WRONLY|O_CREAT|O_EXCL,
S_IREAD|S_IWRITE);
if (target == -1) {
if(errno == EEXIST) {
printf("Target exists. Overwrite? ");
ch = getchar();
if((ch == 'y') || (ch == 'Y'))
target = open(argv[2], O_BINARY|O_WRONLY|O_CREAT|O_TRUNC,
S_IREAD|S_IWRITE);
}
else {
printf("***error ファイル %s をオープンできません\n", argv[2]);
exit(1);
}
}
/*
バッファ領域の確保
*/
fstat(source, &filestat);
count = filestat.st_size;
if((buf = (char *)malloc((size_t)count)) == NULL) {
printf("***error no memory\n");
exit(1);
}
/*
コピー
*/
if ((count = (long)read(source, buf, (int)count)) == -1) {
printf("ファイルの読込に失敗しました\n");
exit(1);
}
if ((count = (long)write(target, buf, (int)count)) == -1) {
printf("ファイルの書き込みに失敗しました\n");
exit(1);
}
/*
ファイルのクローズと領域の開放
*/
close(source);
close(target);
free(buf);
printf("Copy successful\n");
return 0;
}