gpt4 book ai didi

c++ - 在 C++ 中打开多个文件

转载 作者:太空宇宙 更新时间:2023-11-04 15:28:27 25 4
gpt4 key购买 nike

我有这段代码可以在命令行中一次打开多个文件,然后如果它无法打开其中一个文件,它会关闭所有文件并退出。

/* 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 是什么意思?谢谢。

最佳答案

在循环中delete[] fileObj 之后,您需要exit(EXIT_FAILURE),否则您将在下一次迭代时崩溃。这可能就是警告 449 告诉您的内容。

除此之外,代码看起来还不错。但是,如果您希望它在没有这些警告的情况下进行编译,您可以将内部循环变成一个标准的 for 循环,它只使用 loopCount 作为界限。像这样的东西:

for (int i = loopCount; i >= 0; i--) {
fileObj[i].close();
cout << "Closed " << fileNames[i] << "\n";
}

关于c++ - 在 C++ 中打开多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2388118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com