logoISU  

CS 256 - Principles of Structured Design

Summer 2021

Displaying ./code/jun30/writeFile.c

/*

opening a file, and then printing it's contents to another file
called output.txt

*/

#include <stdio.h>
#include <stdlib.h>

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

	if(argc < 2){
		printf("Usage %s file\n", argv[0]);
		exit(1);
	}




	//declaring file pointers
	FILE *fp, *fd;

	fp = fopen(argv[1], "r");
	fd = fopen("output.txt", "w"); //here, we're writing the contents of the file we're reading
								   //into output.txt
	int ch;

	//using fgetc to output each character to the file
	//fgetc takes 1 argument, the file we're reading
	//EOF means "end of file", it's a character at the end of every file
	//that marks the end of the file.
	while ( (ch = fgetc(fp)) != EOF ) {
  		fputc(ch, fd);
	}
	//fputc outputs a single character to a file, it takes two 
	//arguments, the character and the file we're ouputting to

	//closing both files
	fclose(fp);
	fclose(fd);

	return 0;
}