basic file creation and appending.. ofstream vs. WriteFile

This is a discussion on basic file creation and appending.. ofstream vs. WriteFile within the Windows Programming forums, part of the Platform Specific Boards category; Hello, i am making a basic program and I need to create a new file and add a couple lines ...

  1. #1
    Registered User
    Join Date
    Aug 2005
    Posts
    266

    basic file creation and appending.. ofstream vs. WriteFile

    Hello, i am making a basic program and I need to create a new file and add a couple lines to it. (C++)

    I have tried something similar to this, with writefile (WriteFile Function (Windows))

    (i dont have the code with me but this is the gist of it)
    Code:
    string buffer = "line1\nline2";
    HANDLE hf = CreateFile( ..... ); // open with write attribute, Create_always
    LPDWORD lpNumberOfBytesWritten;
    WriteFile(hf, buffer.c_str(), buffer.length(), lpNumberOfBytesWritten, NULL);
    For some reason this code ALWAYS skips the newline character in the buffer, and the file ends up containing the following, which screws up the rest of my program.
    Code:
    line1line2
    Now I am sure that ofstream won't let me down if I use it, but I was wondering if theres any disadvantage to using ofstream opposed to WriteFile since I am only using basic options. This is a windows program, would I run into any problems using ofstream?

    Besides ofstream does anyone see what is wrong with how I am using WriteFile?

    thanks!

  2. #2
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,248
    An end-of-line sequence on windows is "\r\n", not "\n". Had you been using an ofstream, and std::endl, it would have been handled for you automatically.

    I'm confused. If you aren't doing any "funny business" why would you even CONSIDER using a platform-specific function?
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  3. #3
    Registered User
    Join Date
    Aug 2005
    Posts
    266
    ah brewbuck thanks, I didn't notice this detail!!

    now, why am I using a platform specific function ? I don't know, I figured since I already had to use other windows stuff that i might as well use WriteFile. It ended me up with a headache thats all.

    thanks again!

Popular pages Recent additions subscribe to a feed

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