I am not sure if you can use for loop like this to pen multiple file array files. Can you please look and tell me is I am doing this right.
1 2 3 4 5 6 7 8 9 10 11 12
//Opens the file, where filenames is an array of files, count is the number of files in the array.
ifstream *OpenFiles(char * const fileNames[], size_t count)
{
int fileCntr;
char *filePntr[] = {"filePntr0", "filePntr1" , "filePntr2", "filePntr3", "filePntr4"};
for (fileCntr = 0; fileCntr < count; fileCntr++)
{
ifstream filePntr[fileCntr](fileNames[fileCntr], ios::in);
if (filePntr.is_open()) ErrorAndExit(fileNames[0]);
}
return (&filePntr);
}
This shouldn't compile. filePntr is of type char**. &filePntr is of type char***. Neither of those make sense if you're returning a pointer to ifstream.
The homework specification states that I should dynamicall allocate memory when opening the file and free it when done with the file.
is new automatically allocate memory and delete[] free it?
I could find any document in www.cplusplus.com about allocating mem and free it.
/* Opens an array of files and returns a pointer to the first
* element (the first file).
*/
ifstream *OpenFiles(char * const fileNames[], size_t count)
{
//Variable declaration and initialization
ifstream *ret = new ifstream[count];
// If no command line arguments, error and exit
if (count <= 1)
{
cerr << "There is no arguments.\n";
//display message and wait for response before exitin
cin.get();
exit(EXIT_FAILURE);
}
//opens the files in the main program arguments
int loopCount;
while (count >= 1)
{
//open the file in a read optional second argument
ret[count].open(fileNames[count]);
//if any of the files fails to open close all the files and exit
if (!ret[count].is_open())
{
cerr << "Failed to open " << fileNames[count] << "\n";
for (loopCount = count; loopCount >= 0; loopCount--)
{
ret[loopCount].close();
delete[] ret[loopCount];
cout << "Closed " << fileNames[loopCount] << "\n";
count = 0;
}
}
count--;
}
return ret;
}