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++.
Thanks!
#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::ofstream for details.
HTH
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.
Avoid doing unnecessary flushes of your buffer, which is done with endl. That is the most "abused" feature of file-writing.
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;
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With