0

I am trying to write some lines to a a txt file through an ATL application. Below is the fragment of code I use:

HANDLE hFile = CreateFile(ofn.lpstrFile, 
            GENERIC_READ | GENERIC_WRITE,
            0,
            NULL, 
            CREATE_ALWAYS,
            FILE_ATTRIBUTE_NORMAL,
            NULL);

        DWORD dwBytesWritten = 0;

        std::list<CString> helpList;
        std::list<CString>::iterator it;
        helpList.push_back(L"First Line\r\n");
        helpList.push_back(L"Second Line");

        for(it=helpList.begin(); it!=helpList.end(); ++it)
            WriteFile( hFile, (*it).GetString(), (*it).GetLength(), &dwBytesWritten, NULL );

        CloseHandle(hFile); 

Notwithstanding everything is working right, nothing is finally written to the file. What should I change in the code?

arjacsoh
  • 8,932
  • 28
  • 106
  • 166
  • 4
    Have you checked that the call to `CreateFile` actually succeeds? The same with the `WriteFile` calls? – Some programmer dude Jul 19 '12 at 10:39
  • Did you close the file handle after writing to it with `CloseHandle(hFile)`? – xaizek Jul 19 '12 at 10:42
  • dwShareMode = Prevents other processes from opening a file or device if they request delete, read, or write access. Assuming that the file which already exists, should not be shared. – hB0 Jul 19 '12 at 10:45
  • Ok, a not fulfilled if-statement above prevented the programm from reaching the given lines of code. After correcting it though, the only line that stands in the txt file looks like : FNUL iNUL rNUL sNUL tNUL SNUL eNUL cNUL oNUL nNUL dNUL. Any idea what provoked that? – arjacsoh Jul 19 '12 at 11:07

1 Answers1

0

Couple of issues:

  1. Close the handle to the file using CloseHandle()
  2. The length argument for WriteFile() is in bytes but you're specifying characters. Since you're using wide chars you need to multiple the length value by the size of the char.
snowdude
  • 3,854
  • 1
  • 18
  • 27