Programming Tips - How can I use CreateFile() to simply open a file for writing?

Date: 2009oct5 Platform: win32 Language: C/C++ Keywords: fopen, OpenFile, simple Q. How can I use CreateFile() to simply open a file for writing? A.
HANDLE OpenForWrite(LPCTSTR szDest) { HANDLE h = CreateFile(szDest // name of the file ,GENERIC_WRITE // access mode ,FILE_SHARE_WRITE // Share mode ,NULL // Security ,CREATE_ALWAYS // Creates a new file. If the file exists, the function overwrites the file and clears the existing attributes. ,FILE_ATTRIBUTE_NORMAL // file attributes ,NULL); // Template if (h == INVALID_HANDLE_VALUE) h = NULL; return h; }
This is the the same as:
FILE *OpenForWriteStd(LPCSTR szDest) { return fopen(szDest, "wb"); }
Except you get a different kind of handle.
void ExampleUse() { LPCSTR szDest = "c:\\myfile.txt"; HANDLE h; if ((h = OpenForWrite(szDest)) == NULL) { // ... Problem ... return; } // ... Write to the handle ... CloseHandle(h); }