Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vue.js/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在C+中使用流写入文件+;_C++ - Fatal编程技术网

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

C++ 在C+中使用流写入文件+;,c++,C++,我想把一些文本输出到一个文件中。我听说流式传输数据比创建一个大字符串并输出数据要好。目前,我正在创建一个大字符串并输出到一个文件。请求提供一个示例代码,说明如何使用C++来流数据和写入文件。 谢谢 #include <fstream> int main() { std::ofstream fout("filename.txt"); fout << "Hello"; fout << 5; fout << std::endl;

我想把一些文本输出到一个文件中。我听说流式传输数据比创建一个大字符串并输出数据要好。目前,我正在创建一个大字符串并输出到一个文件。请求提供一个示例代码,说明如何使用C++来流数据和写入文件。 谢谢

#include <fstream>

int main()
{
   std::ofstream fout("filename.txt");
   fout << "Hello";
   fout << 5;
   fout << std::endl;
   fout << "end";
}
有关详细信息,请参阅上的更多信息


HTH

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

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

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

#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;
}
#包括
int main(int argc,char*argv[])
{
如果(argc>1)
{
std::of流输出文件(argv[1]);
如果(输出文件)
{

outputFile为什么不提供到目前为止您所拥有的?可能是您已经快到了…!问题是您的代码是否有任何性能问题?如果没有,我就这样离开它。
#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;
}