gpt4 book ai didi

c++ - 有没有一种 C++ 方法可以用任何类型的数据写入文件?

转载 作者:行者123 更新时间:2023-11-27 22:30:14 25 4
gpt4 key购买 nike

比如C中的这个函数:

size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream );

我查看了 C++ 文件流并找到了这个:

ostream& write ( const char* s , streamsize n );

这个只接受 char* 而不是 void*

但是如果我在 C++ 中使用 C 风格的 fwrite 函数真的很重要吗?

最佳答案

除非我误解了您的问题,否则您可能正在寻找流。有许多处理不同工作的风格,比如输出到文件:

#include <cstdlib>
#include <fstream>
#include <string>
using namespace std;


int main()
{
ofstream f("c:\\out.txt");

const char foo[] = "foo";
string bar = "bar";
int answer = 42;

f << foo << bar<< answer;

return 0;
}

...像使用 printf 一样构建字符串:

#include <cstdlib>
#include <sstream>
#include <string>
#include <iostream>
using namespace std;


int main()
{
stringstream ss;

const char foo[] = "foo";
string bar = "bar";
int answer = 42;

ss << foo << bar<< answer;
string my_out = ss.str();

return 0;
}

...他们甚至可以处理您自己的类型,如果您告诉他们如何:

#include <cstdlib>
#include <string>
#include <iostream>
using namespace std;

class MyGizmo
{
public:
string bar_;
int answer_;

MyGizmo() : bar_("my_bar"), answer_(43) {};
};

ostream& operator<<(ostream& os, const MyGizmo& g)
{
os << g.bar_ << " = " << g.answer_;
return os;
}
int main()
{
MyGizmo gizmo;
cout << gizmo;

return 0;
}

关于c++ - 有没有一种 C++ 方法可以用任何类型的数据写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3531811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com