如何用CPP中的地图内容覆盖文件

how to overwrite the file with map contents in cpp

本文关键字:覆盖 文件 地图 何用 CPP      更新时间:2023-10-16

我正在尝试用地图内容覆盖我的文本文件,任何人都可以给我一个想法直到现在我做了

#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