9

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!

2
  • 2
    Why don't you provide what you have so far? It could be that you're almost there...! Commented Mar 4, 2011 at 13:11
  • Question is are you having any performance problems with your code? if not, I would leave it just like that. Commented Mar 4, 2011 at 13:11

2 Answers 2

23
#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

Sign up to request clarification or add additional context in comments.

Comments

7

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.