The Windows File Management 23




Open a File for Reading Program Example


The following example uses CreateFile() to open an existing file for reading and ReadFile() to characters synchronously from the file. In this case, CreateFile() succeeds only if the specified file already exists in the current directory. A subsequent call to open this file with CreateFile() will succeed if the call uses the same access and sharing modes. You can use the file you created with the previous WriteFile() example to test this example.




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>

#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);


// Provide enough room for Unicode/multibyte lol

#define BUFFER_SIZE 200


int wmain(int argc, WCHAR *argv[])


    HANDLE hFile;

    DWORD dwBytesRead = 0;

    WCHAR ReadBuffer[BUFFER_SIZE] = {0};



    // Verify the argument number

    if(argc != 2)


        // The file must be available

        wprintf(LNo argument supplied!\n);

        wprintf(LUsage: %s <file_name_to_be_read>\n, argv[0]);

        wprintf(LExample: %s gedik.txt\n, argv[0]);

        wprintf(L         the file must exist...\n);

        return 1;



    hFile = CreateFile(argv[1],                // file to open

                       GENERIC_READ,          // open for reading

                       FILE_SHARE_READ,    // share for reading

                       NULL,                  // default security

                       OPEN_EXISTING,         // existing file only

                       FILE_ATTRIBUTE_NORMAL, // normal file

                       NULL);                 // no attr. template


    if (hFile == INVALID_HANDLE_VALUE)



        return 1;



            wprintf(L%s successfully opened for reading!\n, argv[1]);


    // Read one character less than the buffer size to save room for

    // the terminating NULL character.

    // Take note also for Unicode/multibyte size

    if(ReadFile(hFile, ReadBuffer, (BUFFER_SIZE-1), &dwBytesRead, NULL)== FALSE)




        return 1;



            wprintf(LReadFile() is pretty fine!\n);


    if (dwBytesRead > 0)


        // NULL character



        wprintf(LString read from %s file, %d bytes: \n, argv[1], dwBytesRead);

        // Why we need to add 1???

        wprintf(L%s\n, ReadBuffer+1);




        wprintf(LNo data read from file %s\n, argv[1]);



    if(CloseHandle(hFile) != 0)

            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();









        (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);







To test this program, firstly we create a simple text file, mytestfile.txt with some content on C drive.


Open a File for Reading Program Example: A simple text file for testing


Then we run the program using the previously created text file name as the argument.


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




< Windows Files 22 | Win32 Programming | Win32 File Index | Windows Files 24 >