用c ++编写文本/二进制文件最优雅的方法是什么? [英] What is the most elegant way to write a text/binary file with c++?

查看:135
本文介绍了用c ++编写文本/二进制文件最优雅的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在阅读时发现了一些很好的结果,例如:用迭代器和预分配读取txt 读入容器。所以我想知道如何写一个最优雅的std ::字符串到一个文件?

编辑:当阅读我可以预先分配空间的字符串通过seek和tellg,因为我知道字符串的大小,我怎么能告诉文件系统我要写多少?

解决方案

这里有一个小例子关于如何输出一个 std :: string ,但你应该阅读 fstream

  #include< iostream> 
#include< fstream>
#include< string>
$ b int main(int argc,char * argv [])
{

std :: string s(writemeout);
std :: ofstream outfile(output.txt);
if(!outfile.is_open()){
std :: cerr<< 无法打开'output.txt'<<的std :: ENDL;
返回-1;
}

outfile<< s<的std :: ENDL;
outfile.close();
返回0;
}


I found some good results on reading e.g.: Read txt with iterators and preallocation, or read into containers. So I wondered how would I write most elegant a std::string into a file?

Edit: When reading I can preallocate space for the string via seek and tellg, since I know the size of the string, how could I tell the filesystem how much I want to write?

解决方案

Here's a tiny example on how to output a std::string, but you should really read up on fstream

#include <iostream>
#include <fstream>
#include <string>

int main(int argc, char *argv[])
{

  std::string s("writemeout");
  std::ofstream outfile("output.txt");
  if(!outfile.is_open()) {
    std::cerr << "Couldn't open 'output.txt'" << std::endl;
    return -1;
  }

  outfile << s << std::endl;
  outfile.close();
  return 0;
}

这篇关于用c ++编写文本/二进制文件最优雅的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆