dcsimg
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6

Thread: writing and appending to file lots of times takes to long how to improve ?

  1. #1
    Join Date
    Aug 2006
    Posts
    230

    writing and appending to file lots of times takes to long how to improve ?

    Hello all

    im using ofstream to writing to file and then appending strings to file

    the problem is that im writing to file many times some thing like 5000+ times ( the reason is it writing to file directories and files )

    the code open file and writing to it looks like this :

    ofstream myfile ("my_log.txt",ios::app);

    if (myfile.is_open())

    {

    myfile << c <<".\n";

    myfile.close();

    }



    how can i improve the speed of writing to file ?

  2. #2
    Join Date
    May 2003
    Location
    San Antonio TX
    Posts
    380

    Re: writing and appending to file lots of times takes to long how to improve ?

    Try to reduce the number of times you write to the file.

    Use a buffer. Instead of writing to the file, write to an internal buffer and then only write to the file when the buffer is full.
    John 3:16
    For God so loved the world ...

  3. #3
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,554

    Re: writing and appending to file lots of times takes to long how to improve ?

    Opening and closing the file repeatedly isn't going to help you either.

  4. #4
    Join Date
    Aug 2002
    Location
    Cluj-Napoca,Romania
    Posts
    3,496

    Re: writing and appending to file lots of times takes to long how to improve ?

    Another thing you can do is move all the file operations in a different thread. The downside is that you will consume more memory by doing this and, if witting from multiple threads, you might need additional code to ensure your data is written in the correct order.
    Har Har

  5. #5
    Join Date
    Aug 2006
    Posts
    230

    Re: writing and appending to file lots of times takes to long how to improve ?

    can you point me to example that implement buffer ?

  6. #6
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: writing and appending to file lots of times takes to long how to improve ?

    Just write to an ostringstream rather than an ofstream. When you're ready, dump the ostringstream contents into the ofstream all at once.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)