在C ++中处理文件映射 [英] Handling map of files in c++
问题描述
我需要同时写入一堆文件,所以我决定使用 map< string,ofstream>
。
I need to write to a bunch of files simultaneously, so I decided to use map <string, ofstream>
.
map<string, ofstream> MyFileMap;
我采用 vector< string> FileInd
,由 a b c
组成,然后尝试使用以下命令打开我的文件:
I take a vector<string> FileInd
, which consists of, say "a" "b" "c"
, and try to open my files with:
for (vector<string>::iterator it = FileInd.begin(); iter != FileInd.end(); ++it){
...
MyFileMap[*it].open("/myhomefolder/"+(*it)+".");
}
我得到了错误
request for member 'open' in ..... , which is of non-class type 'std::ofstream*'
我试图切换到
map<string, ofstream*> MyFileMap;
但是它也不起作用。
有人可以帮忙吗?
谢谢。
说明:
我都尝试过
map< string,ofstream> MyFileMap;
map< string,ofstream *> MyFileMap;
两者都
.open
->打开
这四个变体都不起作用。
neither of 4 variants work.
解决方案(在下面的Rob代码中建议):
基本上,我忘记了 ,以下对我有用:
Basically, I forgot "new", the following works for me:
map<string, ofstream*> MyFileMap;
MyFileMap[*it] = new ofstream("/myhomefolder/"+(*it)+".");
推荐答案
std :: map< std :: string,std :: ofstream>
可能无法工作,因为 std :: map
要求其数据类型为可分配的, std :: ofstream
不是。或者,数据类型必须是指向ofstream的指针-原始指针或智能指针。
std::map<std::string, std::ofstream>
can't possibly work, because std::map
requires its data type to be Assignable, which std::ofstream
isn't. In the alternative, the data type must be a pointer to ofstream -- either a raw pointer or a smart pointer.
这是我使用C +的方式+11功能:
Here is how I would do it, using C++11 features:
#include <string>
#include <map>
#include <fstream>
#include <iostream>
#include <vector>
int main (int ac, char **av)
{
// Convenient access to argument array
std::vector<std::string> fileNames(av+1, av+ac);
// If I were smart, this would be std::shared_ptr or something
std::map<std::string, std::ofstream*> fileMap;
// Open all of the files
for(auto& fileName : fileNames) {
fileMap[fileName] = new std::ofstream("/tmp/xxx/"+fileName+".txt");
if(!fileMap[fileName] || !*fileMap[fileName])
perror(fileName.c_str());
}
// Write some data to all of the files
for(auto& pair : fileMap) {
*pair.second << "Hello, world\n";
}
// Close all of the files
// If I had used std::shared_ptr, I could skip this step
for(auto& pair : fileMap) {
delete pair.second;
pair.second = 0;
}
}
和第二节经文,在C ++ 03中:
and the 2nd verse, in C++03:
#include <string>
#include <map>
#include <fstream>
#include <iostream>
#include <vector>
int main (int ac, char **av)
{
typedef std::map<std::string, std::ofstream*> Map;
typedef Map::iterator Iterator;
Map fileMap;
// Open all of the files
std::string xxx("/tmp/xxx/");
while(av++,--ac) {
fileMap[*av] = new std::ofstream( (xxx+*av+".txt").c_str() );
if(!fileMap[*av] || !*fileMap[*av])
perror(*av);
}
// Write some data to all of the files
for(Iterator it = fileMap.begin(); it != fileMap.end(); ++it) {
*(it->second) << "Hello, world\n";
}
// Close all of the files
for(Iterator it = fileMap.begin(); it != fileMap.end(); ++it) {
delete it->second;
it->second = 0;
}
}
这篇关于在C ++中处理文件映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!