I have this code to open multiple files one at a time that is given at the command line, and then if it cannot open one of the files, it closes all the files and exits.
/* Opens an array of files and returns a pointer to the first
* element (the first file).
*/
ifstream *OpenFiles(char * const fileNames[], size_t count)
{
/* If no command line arguments, error and exit */
if (count == 0) {
cerr << "Invalid number of arguments.";
exit(EXIT_FAILURE);
}
ifstream *fileObj;
fileObj = new ifstream[count];
if (fileObj == NULL) {
cerr << "Failed to create space for files";
exit(EXIT_FAILURE);
}
/* Opens one file at a time and closes all files if there is an
* error opening any file.
*/
for (int loopCount = 0; loopCount < (int)count; loopCount++) {
fileObj[loopCount].open(fileNames[loopCount], ios::out);
if (!fileObj[loopCount].is_open()) {
cerr << "Failed to open " << fileNames[loopCount] << "\n";
for (; loopCount >= 0; loopCount--) {
fileObj[loopCount].close();
cout << "Closed " << fileNames[loopCount] << "\n";
}
delete[] fileObj;
}
}
return fileObj;
}
I am doing this for homework and my teacher has another checker we have to submit to and gives me these types of warnings:
Assign8_1.cpp(44): error 445: (Warning -- Reuse of for loop variable 'loopCount' at 'line 40' could cause chaos)
return fileObj;
Assign8_1.cpp(51): error 850: (Info -- for loop index variable 'loopCount' whose type category is 'integral' is modified in body of the for loop that began at 'line 40')
return fileObj;
Assign8_1.cpp(51): error 449: (Warning -- Pointer variable 'fileObj' previously deallocated [Reference: file Assign8_1.cpp: lines 30, 48])
Assign8_1.cpp(30): error 831: (Info -- Reference cited in prior message)
Assign8_1.cpp(48): error 831: (Info -- Reference cited in prior message)
}
Assign8_1.cpp(63): error 818: (Info -- Pointer parameter 'files' (line 55) could be declared as pointing to const)
}
Starting with the first warning, I was wondering why I shouldn't use my loopCount variable twice the way I do in my code. That was the way I thought it would work, keeping track of which file I am looking at, opening, and closing it appropriately.
Does anyone know what error 449 means? Thanks.