/* Week 3 code sample for CPS125. Ferworn Fall 06
Simple File Input and Output

There is an important concept in the C programming language. The concept is that of a "stream".
If you think about what most people call a stream you won't be too far off. A stream flows with
water. It comes from some place (often called a source) and it goes to some place. 
This is very similar to streams in C--they are places that data comes from and goes to. When
you start a main function you already have 3 streams defined automatically for you. The
stream "stdin" is an input stream and is attached to the keyboard. "stdout" is another stream and
sends output to your screen. The last stream is "stderr" and is also attached to the screen and is the
source of error messages.

You can define your own streams. You tell C what you want to read from or write to.

Here is a bit of a complete example:
*/

#include <stdio.h>
int main()
{
	
	FILE *in, 	/* a FILE pointer which will point at the input stream */	
		 *out;	/* a FILE pointer which will point at the output stream */	
	 	
	short int ival;		/* just an integer variable */	
	
	in = fopen("input.txt","r");	/* attempt to associate in with the input stream coming from	
									the file input.txt */	
	/* in will be NULL if the file could not be opened...maybe it doesn't exist */	
	if(in == NULL)	
	{	
		fprintf(stderr,"Could not open input file\n"); /* tell people about it */	
		exit(0);										/* leave execution */	
	}
	fscanf(in,"%d",&ival);		/* read from the in stream using fscanf and the pointer in */	
	fclose(in);					/* we are finished reading so we should close the stream in */	
	
	out = fopen("output.txt","w");	/* attempt to associate out with the output stream going to	
									the file output.txt */	
	/* out will be NULL if the file could not be opened...maybe there is a permissions problem */	
	if(out == NULL)	
	{	
		fprintf(stderr, "Could not open output file\n");	
		fclose(in);				/* if we got here we must have opened the in stream */	
		exit(0);	
	}
	fprintf(out,"%d",ival);		/* output the value to the out stream */	
	fclose(out);
}