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

  1. #1
    Registered User
    Join Date
    Mar 2008

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

    how can i improve the speed of writing to file ?

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Farncombe, Surrey, England
    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].

    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
    Join Date
    Oct 2007
    Inside my computer
    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