在 C++ 中使用流写入文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5194119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:38:50  来源:igfitidea点击:

writing to a file using stream in C++

c++

提问by venkysmarty

I want to some text to output to a file. I heard that it is better to stream the data rather than creating a large string and outputing that. Presently I am creating a large string and outputing to a file. Request to provide an sample code on how to stream a data and write to a file using C++.

我想要一些文本输出到文件。我听说最好是流式传输数据,而不是创建一个大字符串并输出它。目前我正在创建一个大字符串并输出到一个文件。请求提供有关如何使用 C++ 流式传输数据和写入文件的示例代码。

Thanks!

谢谢!

回答by Armen Tsirunyan

#include <fstream>

int main()
{
   std::ofstream fout("filename.txt");
   fout << "Hello";
   fout << 5;
   fout << std::endl;
   fout << "end";
}

Your file now contains this:

您的文件现在包含以下内容:

Hello5 
end

See more info on std::ofstreamfor details.

有关详细信息,请参阅有关std::ofstream的更多信息。

HTH

HTH

回答by CashCow

File writing already uses buffering. If it is not efficient for you, you can actually modify the filebuf, eg increase its size or use a custom one.

文件写入已经使用缓冲。如果它对您来说效率不高,您实际上可以修改filebuf,例如增加其大小或使用自定义的。

Avoid doing unnecessary flushes of your buffer, which is done with endl. That is the most "abused" feature of file-writing.

避免对缓冲区进行不必要的刷新,这是使用 endl 完成的。这是文件写入最“滥用”的功能。

The simplest way to create a file-stream for outputting is:

创建用于输出的文件流的最简单方法是:

#include <fstream>

int main( int argc, char * argv[])
{
   if( argc > 1 )
   {
      std::ofstream outputFile( argv[1] );
      if( outputFile )
      {
         outputFile << 99 << '\t' << 158 << '\n'; // write some delimited numbers
         std::vector< unsigned char > buf;
         // write some data into buf
         outputFile.write( &buf[0], buf.size() ); // write binary to the output stream
      }
      else
      {
         std::cerr << "Failure opening " << argv[1] << '\n';
         return -1;
      }
   }
   else
   {
      std::cerr << "Usage " << argv[0] << " <output file>\n";
      return -2;
   }
   return 0;
}