The Windows File Management 22






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[] = L"This is a test string to be written.";

    DWORD dwBytesToWrite = (DWORD)wcslen(DataBuffer);

    DWORD dwBytesWritten = 0;



    // Verify the argument

    if(argc != 2)


        wprintf(L"No argument supplied!\n");

        wprintf(L"Usage: %s <file_name_to_be_wriiten>\n", argv[0]);

        wprintf(L"Example: %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)



        return 1;



            wprintf(L"%s was successfully created!\n", argv[1]);


    wprintf(L"Writing %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




            if(CloseHandle(hFile) == 0)



                        wprintf(L"Closing the hFile handle...\n");


            return 1;



                  wprintf(L" Writing...\n");



    wprintf(L"Wrote %d bytes to %s successfully.\n", dwBytesWritten, argv[1]);


    if(CloseHandle(hFile) == 0)



            wprintf(L"Closing 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();









        (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, L"Error", MB_OK);






Build and run the project. The following screenshot is a sample output.


Open a File for Writing Program Example: A sample console program output in action


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


Open a File for Writing Program Example: the mytestfile.txt file's content as expected





< Windows Files 21 | Win32 Programming | Win32 File Index | Windows Files 23 >