Opening a File for Reading or Writing
The CreateFile() function can create a new file or open an existing file. You must specify the file name, creation instructions, and other attributes. When an application creates a new file, the operating system adds it to the specified directory.
Open a File for Writing Program Example
The following example uses CreateFile() to create a new file and open it for writing and WriteFile() to write a simple string synchronously to the file. A subsequent call to open this file with CreateFile() will fail until the handle is closed.
Create a new empty Win32 console application project. Give a suitable project name and change the project location if needed.
Then, add the source file and give it a suitable name.
Next, add the following source code.
#include <windows.h>
#include <stdio.h>
// A safer version for string manipulation
#include <strsafe.h>
// A prototype that receives a function name, displaying
// system error code and its respective message
void DisplayErrorBox(LPTSTR lpszFunction);
int wmain(int argc, WCHAR *argv[])
{
HANDLE hFile;
WCHAR DataBuffer[] = LThis is a test string to be written.;
DWORD dwBytesToWrite = (DWORD)wcslen(DataBuffer);
DWORD dwBytesWritten = 0;
wprintf(L\n);
// Verify the argument
if(argc != 2)
{
wprintf(LNo argument supplied!\n);
wprintf(LUsage: %s <file_name_to_be_wriiten>\n, argv[0]);
wprintf(LExample: %s C:\\Mytestfile.doc\n, argv[0]);
return 1;
}
hFile = CreateFile((LPCWSTR)argv[1], // name of the write
GENERIC_WRITE, // open for writing
0, // do not share
NULL, // default security
CREATE_ALWAYS, // overwrite existing
FILE_ATTRIBUTE_NORMAL, // normal file
NULL); // no attr. template
if (hFile == INVALID_HANDLE_VALUE)
{
DisplayErrorBox(LCreateFile());
return 1;
}
else
wprintf(L%s was successfully created!\n, argv[1]);
wprintf(LWriting %d bytes to %s.\n, dwBytesToWrite, argv[1]);
// This loop would most likely never repeat for this synchronous example.
// However, during asynchronous writes the system buffer may become full,
// requiring additional writes until the entire buffer is written
while (dwBytesWritten < dwBytesToWrite)
{
if(FALSE == WriteFile(hFile, // open file handle
DataBuffer + dwBytesWritten, // start of data to write
// Note the Unicode/multibyte size!
2*(dwBytesToWrite - dwBytesWritten), // number of bytes to write
&dwBytesWritten, // number of bytes that were written
NULL) // no overlapped structure
)
{
DisplayErrorBox(LWriteFile());
if(CloseHandle(hFile) == 0)
DisplayErrorBox(LCloseHandle());
else
wprintf(LClosing the hFile handle...\n);
return 1;
}
else
wprintf(L Writing...\n);
}
wprintf(LWrote %d bytes to %s successfully.\n, dwBytesWritten, argv[1]);
if(CloseHandle(hFile) == 0)
DisplayErrorBox(LCloseHandle());
else
wprintf(LClosing the hFile handle...\n);
return 0;
}
void DisplayErrorBox(LPTSTR lpszFunction)
{
// Retrieve the system error message for the last-error code
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
// Display the error message and clean up
lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, (lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(WCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf, LocalSize(lpDisplayBuf) / sizeof(WCHAR), L%s failed with error %d: %s, lpszFunction, dw, lpMsgBuf);
MessageBox(NULL, (LPCTSTR)lpDisplayBuf, LError, MB_OK);
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
}
Build and run the project. The following screenshot is a sample output.

The following is the mytestfile.txt file's content as expected.
