【发布时间】:2010-03-05 16:09:50
【问题描述】:
我有这段代码可以在命令行中一次打开多个文件,然后如果它无法打开其中一个文件,它会关闭所有文件并退出。
/* 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;
}
我这样做是为了做家庭作业,我的老师有另一个检查员我们必须提交给我,并给了我这些类型的警告:
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)
}
从第一个警告开始,我想知道为什么我不应该像在代码中那样使用我的 loopCount 变量两次。这就是我认为它会工作的方式,跟踪我正在查看的文件,适当地打开和关闭它。
有人知道错误 449 是什么意思吗?谢谢。
【问题讨论】:
-
出于好奇,此输出似乎来自 Gimpel lint 工具之一。
标签: c++