20131117【C言語】ファイルをコピーする

お題

ファイルをコピーする

 

ソース

#include <stdio.h>

#include <stdlib.h>

 

int main(int argc, char *argv[])

{

union u_type {

int i;

char ch;

} var;

 

FILE *fp1, *fp2;

 

/* Check arguments */

if (argc != 3) {

fprintf(stderr, "Usage: <Program Name> <Source file> <Target file>.\n");

exit(1);

}

 

/* Open input file */

if *1 == NULL)  {

fprintf(stderr, "Error while opening input file.\n");

exit(1);

}

 

/* Open target file */

if *2 == NULL) {

fprintf(stderr, "Error while opening target file.\n");

exit(1);

}

 

/* Read input file */

while(!feof(fp1)) {

var.ch = fgetc(fp1);

if (var.i == EOF) {

break;

}

 

fputc(var.ch, fp2);

}

 

 

/* Close file */

fclose(fp1);

fclose(fp2);

 

return 0;

}

 

実行結果

# cat input.txt 

1234567890

# ./a.out input.txt output.txt

# cat output.txt 

1234567890

 

*1:fp1 = fopen(argv[1], "r"

*2:fp2 = fopen(argv[2], "w"