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

  1. #1
    Registered User
    Join Date
    Mar 2008
    Posts
    58

    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 :

    Code:
    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
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    You could try not to open and close the log file every time you log some amount of text.

    If instead, you open the file once (at start of day) and close it at the end of time. If you still want to ensure that the file-content is always up to date, use the ostream::flush() function [although this will somewhat reduce the benefits of not opening and closing the file every time - but there is still a benefit].

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    The later solution would be to keep the file buffered in memory and only write to the file when you need to. Trickier, but certainly faster.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. appending text to existing text file
    By kpax in forum C Programming
    Replies: 8
    Last Post: 05-28-2008, 08:46 AM
  2. Basic program design, passing pointer to a function
    By heras in forum C Programming
    Replies: 14
    Last Post: 04-02-2008, 03:21 AM
  3. Writing to File?
    By mvision in forum C Programming
    Replies: 8
    Last Post: 11-27-2001, 09:30 PM