[EMAIL PROTECTED] wrote:
Hi,

I am trying to do some file I/O. The scenario I am aiming for is to create a file if it doesn’t exist, append to it if it exists as well as allowing for writes to the file from multiple threads.

Since you are coding in C++ have you considered using iostreams for
this part of the project? The Apache C++ Standard Library provides
as an extension thread-safe iostream objects -- see the demo below.

Btw., only the least significant 8 bits of the value returned from
main() (or passed to exit()) are made available to the invoking
process, so values like -1 will end up being sliced or truncated
(in the case of -1 to 255).

Martin


#include <fstream>
#include <string>

int main ()
{
    std::ofstream logfile ("test.txt", std::ios::app | std::ios::out);

    // STDCXX extension: make logfile thread safe
    logfile.unsetf (std::ios::nolock | std::ios::nolockbuf);

    if (!logfile)
        return 1;

    std::string output ("String 1");

    // output string as a single atomic operation
    logfile << output;

    logfile.close ();
    logfile.open ("test.txt", std::ios::app | std::ios::out);

    if (!logfile)
        return 2;

    output.assign ("String 2");

    logfile << output;
}

Reply via email to