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.
Example: Open a File for Writing
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.
void main(int argc, CHAR *argv)
char DataBuffer = "This is a test string to be written.";
DWORD dwBytesToWrite = (DWORD)strlen(DataBuffer);
DWORD dwBytesWritten = 0;
// Verify the argument
if(argc != 2)
printf("ERROR:\tIncorrect number of arguments!\n\n");
printf("%s <file_name>\n", argv);
hFile = CreateFile(argv, // file name to 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)
printf("Could not open %s file, error %d\n", argv, GetLastError());
printf("Writing %d bytes to %s.\n", dwBytesToWrite, argv);
// 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
dwBytesToWrite - dwBytesWritten, // number of bytes to write
&dwBytesWritten, // number of bytes that were written
NULL) // no overlapped structure
printf("Could not write to %s file, error %d\n", argv, GetLastError());
printf("Wrote %d bytes to %s successfully.\n", dwBytesWritten, argv);
To test this program, we copy the executable to C: and create two files named testing.txt and testing.doc. We put both files at C:
The file to be opened and written can have a relative path as shown in the following screenshot.
The Unicode version can be found in the download page (project samples).