4

我在一个目录中有一堆文本文件,每个文本文件都命名为“info1.txt”、“info2.txt”等。我将如何打开 ifstream 对象数组中的所有文本文件,而不必在其中硬编码所有文本文件名?我知道下面的代码不起作用,但我认为它传达了我想要做什么的想法,如果它确实起作用:

ifstream myFiles[5];
for(int i = 0; i < 5; i++){
    myFiles[i].open("info" + i + ".txt");
}

我知道解决方案可能很简单,但经过大量研究、反复试验,我仍然没有弄清楚。谢谢!

4

5 回答 5

7

为了构建文件名,我会使用std::ostringstreamand operator<<

如果您想使用容器类(例如,因为您在编译时不知道'sstd::vector的数组有多大),因为不可复制,您不能使用但可以使用or ; 例如:ifstreamstd::ifstreamvector<ifstream>vector<shared_ptr<ifstream>>vector<unique_ptr<ifstream>>

vector<shared_ptr<ifstream>> myFiles;
for (int i = 0; i < count; i++)
{
    ostringstream filename;
    filename << "info" << i << ".txt";
    myFiles.push_back( make_shared<ifstream>( filename.str() ) );        
}

使用unique_ptr(和 C++11 移动语义):

vector<unique_ptr<ifstream>> myFiles;
for (int i = 0; i < count; i++)
{
    ostringstream filename;
    filename << "info" << i << ".txt";
    unique_ptr<ifstream> file( new ifstream(filename.str()) );
    myFiles.push_back( move(file) );
}

unqiue_ptr比 更有效shared_ptr,因为unique_ptr它只是一个可移动指针,它没有引用计数(因此开销比 少shared_ptr)。unique_ptr因此,在 C++11 中,您可能希望ifstream' 不在vector容器外共享。

于 2012-10-19T07:32:43.003 回答
5

我猜,问题是关于动态创建文件名的部分。

一个简单的解决方案是使用std::ostringstream来做到这一点:

ifstream myFiles[5];
for(int i = 0; i < 5; i++){
    ostringstream filename;
    filename << "info" << i ".txt";
    myFiles[i].open(filename.str());
}

std::string如果您的库太旧,无法在调用中接受参数,open则使用

    myFiles[i].open(filename.str().c_str());
于 2012-10-19T07:20:50.650 回答
3

你的想法应该有一个小的改变:

myFiles[i].open((std::string("info") + itoa(i) + ".txt").c_str());
             // ^^^^^^^^^^^           ^^^^

另请注意,您不能使用std::vector,因为ifstream它不是可复制的对象。所以继续使用数组。

于 2012-10-19T07:19:43.050 回答
1

我通常使用 std::stringstream:

{
  std::stringstream filename;
  filename << "info" << i << ".txt" << std::ends;
  myFiles[i].open(filename.str().c_str());
}
于 2012-10-19T07:21:56.310 回答
0

你可以有一个 ifstream 对象的数组,但是如果你需要一个动态长度,那么你不能这样做,也不会std::vector<ifstream>工作。

所以你需要指针。std::vector<ifstream*>会工作,但你可能会使用 shared_ptr 所以std::vector<shared_ptr<ifstream> >会工作。如果你unique_ptr有空,你可以使用它而不是shared_ptr.

然后必须使用创建每个元素new

您还需要正确创建字符串,您可以使用 aboost::formatostringstream什至老式的sprintf来执行此操作。

顺便说一句,我会搜索 boost 的文件系统库,看看它们是否有更动态的东西ifstream,可以在你的向量中愉快地运行,而不会出现 shared_ptr 的混乱。

于 2012-10-19T07:29:50.660 回答