简体   繁体   中英

Write to a txt file using windows API

I am trying to write some lines to aa 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM