如何用CPP中的地图内容覆盖文件
how to overwrite the file with map contents in cpp
我正在尝试用地图内容覆盖我的文本文件,任何人都可以给我一个想法直到现在我做了
#include <string.h>
#include <iostream>
#include <map>
#include <utility>
using namespace std;
int main()
{
map<int, string> mymap;
mymap[34] = "hero";
mymap[74] = "Clarie";
mymap[13] = "Devil";
for( map<int,string>::iterator i=mymap.begin(); i!=mymap.end(); ++i)
{
cout << (*i).first << ":" << (*i).second << endl;
}
// write the map contents to file .
// mymap &Emp;
FILE *fp;
fp=fopen("bigfile.txt","w");
if(fp!=NULL)
{
for(map<int,string>::iterator it =mymap.begin();it!=mymap.end();++it)
{
fwrite(&mymap,1,sizeof(&mymap),fp);
}
fclose(fp);
}
}
我是新手的容器。我是在正确的过程中吗?在编写地图内容以提交文件时,它在文件中给了我垃圾内容。预先感谢
您的问题:
您对fwrite()
的电话很折断。
fwrite()
将向给定文件编写一系列字节。例如,如果我们想将int
写入文件,我们将需要做类似的事情:
int x = 10;
char text[10];
snprintf(text, 10, "%d", x);
fwrite(text, 1, strlen(text), fp);
对于std::string
,我们需要做类似的事情:
std::string y = "Hello";
fwrite(y.c_str(), 1, y.size(), fp);
另外,您可以使用fprintf()
:
int x = 10;
std::string y = "Hello";
fprintf(fp, "%d:%sn", x, y.c_str());
让我们使用C 工具代替C工具:
如果我们使用C 的std::ofstream
,那么事情要简单得多。实际上,该代码看起来几乎与我们使用std::cout
的方式相同。
#include <cassert>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <utility>
using namespace std;
int main() {
map<int, string> mymap;
mymap[34] = "hero";
mymap[74] = "Clarie";
mymap[13] = "Devil";
for(map<int,string>::iterator i=mymap.begin(); i!=mymap.end(); ++i)
cout << i->first << ":" << i->second << "n";
// write the map contents to file.
std::ofstream output("bigfile.txt");
assert(output.good());
for(map<int,string>::iterator it =mymap.begin();it!=mymap.end();++it)
output << it->first << ":" << it->second << "n";
}
这将输出到屏幕并写入bigfile.txt
:
13:Devil
34:hero
74:Clarie
相关文章:
- 使用ios:ate写入到流会覆盖现有文件
- 如何在 c++ 中覆盖相同的文本文件
- 每个文件(理想情况下是每个部分)的 clang 格式样式覆盖
- C++删除或覆盖文件中的现有信息
- 使用 tellg() 和 seekp() 覆盖文件
- 如何用CPP中的地图内容覆盖文件
- 为什么Visual C++中的“我的语言”翻译器程序不用翻译就覆盖文件
- 是否有任何方法可以仅在覆盖文件的情况下禁用DisplayAlerts
- 使用c++覆盖文件中的文本
- C++流覆盖文件
- 通过覆盖文件"Updating"文件中的行
- 在 C++ 中覆盖文件(不追加)
- C++ 覆盖文件数据
- 如何不覆盖文件,C++日志记录
- 如何使用C ++覆盖文件中的特定数据
- 我正在尝试以二进制写入一些文件,我需要覆盖文件内容,如何覆盖而不是插入
- 在不存在文件损坏风险的情况下覆盖文件
- Ofstream在多次执行时覆盖文件内容
- C++只覆盖文件的一段
- 如何在不关闭文件的情况下覆盖文件