C++ 中的 fstream 数组

0 c++ arrays fstream

我正在用 NTL 库(它是一个 C++ 库)编写一个算法。现在我有 N 个文件要编辑,我必须同时创建/打开它们。我尝试为 N 个文件指针动态分配空间,但代码有问题。代码片段如下所示:

P1 = (char **)calloc(n+1, sizeof(char *));//P1 is used to save file names
for(i=1; i<=n; i++)
{
    P1[i]=(char *)calloc(20, sizeof(char ));
    sprintf(P1[i],"P1_%d.txt",i);
}
ifstream *fin = (ifstream *)calloc(n+1, sizeof(ifstream));
for(i=1; i<=n; i++)
{
    fin[i].open(P[i]);
}
Run Code Online (Sandbox Code Playgroud)

当程序在 linux 中运行时,它告诉我存在分段错误。

由于 N 不大于 200,当我尝试使用

ifstream fin[200]
Run Code Online (Sandbox Code Playgroud)

代替

ifstream *fin = (ifstream *)calloc(n+1, sizeof(ifstream));
Run Code Online (Sandbox Code Playgroud)

程序运行。

我刚学了 C 但没有学 C++,我真的不知道这fstream门课是如何工作的。请问有没有更好的同时打开N个文件的方法?

For*_*veR 5

calloc只会分配内存,但是ifstream是复杂类型。它有构造函数,应该在创建对象时调用。我认为您应该阅读一些有关 C++ 的文档/书籍。您应该使用new expression在 C++ 中分配内存。顺便说一句,如果您使用现代 C++ 编译器,最好使用智能指针(例如unique_ptr)。此外,当您想在对象的编译时计数中存储 unknown 时,最好使用vector。在这种情况下,只使用vector<ifstream>.

// includes for vector and unique_ptr.
#include <vector>
#include <memory>

vector<ifstream> streams;
for (int i = 0; i < n; ++i)
{
   streams.push_back(ifstream(P[i]));
}
Run Code Online (Sandbox Code Playgroud)