20131010【C言語】ファイルをコピーする
お題
ファイルをコピーする
プログラム処理概要
コマンドライン引数でコピー元ファイルとコピー先ファイルを指定し、
ファイルをコピーする
ソース
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE *fp1, *fp2;
char str[80];
/* Check arg count */
if (argc != 3) {
fprintf(stderr, "Usage : <Program Name> <Source File> <Target File>.\n");
exit(1);
}
/* Open Source File */
if *1 == NULL) {
fprintf(stderr, "Error while opening %s.\n", argv[1]);
exit(1);
}
/* Open Target File */
if *2 == NULL) {
fprintf(stderr, "Error while opening %s.\n", argv[2]);
exit(1);
}
while(!feof(fp1)) {
fgets(str, 79, fp1);
if (ferror(fp1)) {
fprintf(stderr, "Error while reading %s.\n", argv[1]);
exit(1);
}
if (!feof(fp1))
fputs(str, fp2);
if (ferror(fp2)) {
fprintf(stderr, "Error while writing to %s.\n", argv[2]);
exit(1);
}
}
/* Close Source File */
if *3 == EOF) {
fprintf(stderr, "Error while closing %s.\n", argv[1]);
exit(1);
}
/* Close Target File */
if *4 == EOF) {
fprintf(stderr, "Error while closing %s.\n", argv[2]);
exit(1);
}
exit(0);
}
実行結果
# ls -ltr in.txt out.txt
ls: cannot access out.txt: No such file or directory
-rw-rw-r-- 1 teru teru 18 Oct 10 04:08 in.txt
# cat in.txt
hoge1
hoge2
hoge3
# ./a.out in.txt out.txt
# cat out.txt
hoge1
hoge2
hoge3
#