/***************************************************************************
 * File:         copyfile.c
 * Status:       05-mar-2008, wlm
 *               17-sep-2010, wlm
 * Functie:      Voorbeeld met declareren en gebruik van files.
 * Beschrijving: Een inputfile wordt gekopieerd naar een opgegeven output file.
 *               Als de outputfile bestaat, wordt gevraagd om deze
 *               wel of niet te overschrijven.
 *               Als de outputfile niet bestaat, wordt deze gemaakt.
 ***************************************************************************/

#include <stdio.h>
#include <stdlib.h> 
#include <ctype.h>
#include <string.h>

void filecopy(FILE * in, FILE * out);

int main(int argc, char *argv[]) {
	FILE *finp, /* file identifier van inputfile */
	*fout; /* file identifier van outputfile */
	char inp;

	if (argc == 1) { /* No arguments stop */
		printf("\n Error: No files to copy from and to are given\n");
		printf("   Use: copyfile fileNameFrom fileNameTo\n\n");
		exit(10);
	}
	if (argc == 2) { /* Only one file name was found */
		printf("\n Error: No file to copy to is given\n");
		printf("   Use: copyfile fileNameFrom fileNameTo\n\n");
		exit(11);
	}
	if (strcmp(argv[1], argv[2]) == 0) { /* Check if filenames are identical */
		printf("\n Error: File names are identical\n");
		printf("   Use: copyfile fileNameFrom fileNameTo\n\n");
		exit(12);
	}

	finp = fopen(argv[1], "r");
	if (finp == NULL) { /* File pointer NULL: Most like file does not exists */
		printf("\n Error: Input file %s does not exists\n\n", argv[1]);
		exit(13);
	}
	fout = fopen(argv[2], "r"); /* Check if file exists */
	if (fout != NULL) { /* File pointer != NULL: File already exists */
		printf(
				"\n Output file %s already exists. Do you want to overwrite (Y/N)? ...",
				argv[2]);
		scanf("%c", &inp);
		inp = toupper(inp);
		if (inp != 'Y') {
			fclose(finp);
			fclose(fout);
			exit(1);
		}
		fclose(fout);
	}
	fout = fopen(argv[2], "w");
	if (fout == NULL) { /* Error opening file for writing */
		fclose(finp);
		printf("\n Output file %s could not be opened for writing.", argv[2]);
		exit(2);
	}

	filecopy(finp, fout);

	fclose(finp);
	fclose(fout);

	return (0);
}

void filecopy(FILE * in, FILE * out) {

	int c;
	while ((c = getc(in)) != EOF)
		putc(c, out);
	return;
}
