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

This is a discussion on writing and appending to file lots of times takes to long how to improve ? within the C++ Programming forums, part of the General Programming Boards category; Hello all im using ofstream to writing to file and then appending strings to file the problem is that im ...

  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をこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,768
    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, 08:30 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21