C++中的流数组

Array of fstream in C++

本文关键字:数组 C++      更新时间:2023-10-16

我正在使用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]);
}

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

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

ifstream fin[200]

而不是

ifstream *fin = (ifstream *)calloc(n+1, sizeof(ifstream));

程序运行。

我刚刚学了C,但没有学C++,我真的不知道fstream课是如何工作的。你能告诉我是否有一些更好的方法可以同时打开N个文件吗?

calloc只会分配内存,但ifstream是复杂类型。它有构造函数,应该在对象创建时调用。我认为你应该阅读一些关于C++的文档/书籍。您应该使用新表达式在C++中分配内存。顺便说一句,如果您使用现代C++编译器,最好使用智能指针(例如unique_ptr(。此外,当您想要在编译时存储未知的对象计数时,最好使用 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]));
}