/* File "CS35files.h"
   This file contains defines some functions that are useful for files.
   It also invokes the   "CS35lib.h"   header  
*/

#include "CS35lib.h"


void rewind (istream& a_file);	
	// To return to the beginning of an input-stream, and "clear" error flags
	// After using ^D to indicat the end of user input from the keyboard,
	//   you should use the command  rewind(cin) to "clear" the cin error flags

int request_and_open_an_in_file (ifstream& in_file, char file_name[ ], int flag);
	// Invoke this procedure to open an in-file (i.e., an ifstream).
	// It will check to be sure your in_file exists, and then return the file's name
	// It returns 1 (TRUE) if open was successful, 0 (FALSE) if unsuccessful

int request_and_open_an_out_file (ofstream& out_file, char file_name[ ], int flag);
	// Invoke this procedure to open an out-file (i.e., an ofstream).
	// It will check to be warn you if the file you're about to open already exists,
	// It then opens the out_file and then return the file's name
	// It returns 1 (TRUE) if open was successful, 0 (FALSE) if unsuccessful

void rewind (istream& a_file)	// The name "rewind" is standard in C
{
	a_file.clear();				//To "clear" the end-of-file flag  
	a_file.seekg(0, ios::beg);	//To go to the beginning of the file
}

void getline (istream& afile, char str[]);

int request_and_open_an_in_file (ifstream& in_file, char file_name[], int flag=0)
{
	char answer;
	cout << "What is the name of the in-file to open? ";
	cin  >> file_name;
	in_file.open (file_name);
	while (in_file.fail() )
	{
		in_file.clear ();
		cout << "That file does not exist.  Do you want try another file (Y?N)? ";
		answer = get_Y_or_N();
		if (answer == 'N')
		{ if (flag == 1) return 0; else exit (0); }
		cout << "Enter another name: ";
		cin >> file_name;
		in_file.open(file_name);
	}
	return 1;
}

	
int request_and_open_an_out_file (ofstream& out_file, char file_name[ ],int flag = 0)
{
	ifstream dummy;
	char answer;
	
	cout << "What is the name of the out-file to open? ";
	cin  >> file_name;
	dummy.open (file_name);
	answer = 'N';
	while ( !dummy.fail() && (answer == 'N') )
	{
		cout << "That file already exists.  Open it anyway? (Y/N): ";
		answer = get_Y_or_N();
		if (answer == 'N')
		{
			dummy.close();
			cout << "Do you want try opening a different out-file (Y/N)? ";
			answer = get_Y_or_N();
			if (answer == 'N')
			{ if (flag == 1) return 0; else exit (0); }
			cout << "Enter another name: ";
			cin >> file_name;
			dummy.open (file_name);
		}
	}
	dummy.close();
	out_file.open(file_name);
	return 1;
}

void getline (istream& afile, char str[])
{
	 afile.getline(str, 256);
}

	

