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};

 

    printf("\n");

    // Verify the argument number

    if(argc != 2)

    {

        // The file must be available

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

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

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

    {

        DisplayErrorBox(L"CreateFile()");

        return 1;

    }

      else

            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)

    {

        DisplayErrorBox(L"ReadFile()");

        CloseHandle(hFile);

        return 1;

    }

      else

            wprintf(L"ReadFile() is pretty fine!\n");

 

    if (dwBytesRead > 0)

    {

        // NULL character

        ReadBuffer[dwBytesRead+1]='\0';

 

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

        // Why we need to add 1???

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

    }

    else

    {

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

    }

 

    if(CloseHandle(hFile) != 0)

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

      else

            DisplayErrorBox(L"CloseHandle()");

 

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

 

    LocalFree(lpMsgBuf);

    LocalFree(lpDisplayBuf);

}

 

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 >