tags:

views:

35

answers:

1

It's quite a simple C code to read a file text, I've done this other times but don't know why now the ReadFile function keeps returning FALSE meaning it fails.

Obviously the text file input.txt exists and the CreateFile function succeeds (or at least doen't return INVALID_HANDLE_VALUE

#include <stdio.h>
#include <windows.h>

int main(int argc, char *argv[])
{
    char ReadBuffer[256] = {0};
    HANDLE hFile1;
    int n = 0;
    DWORD bytesread = 5;

    printf("Press enter to read the file 'input.txt' ... ");
    getch();

    if ( (hFile1 = CreateFile(TEXT("input.txt"), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL) == INVALID_HANDLE_VALUE))
    {
        printf("INVALID_HANDLE_VALUE");
        return -1;
    }

    if ( ReadFile(hFile1, ReadBuffer, bytesread, &bytesread, NULL) == FALSE )
    {
        printf("ReadFile ERROR");
        CloseHandle(hFile1);
        return -2;
    }

    printf("\n\nRead bytes: %d \n\n", bytesread);


    CloseHandle(hFile1);
    return 0;
}
+3  A: 

The error is a simple misplacement of a parenthesis.

if ( (hFile1 = CreateFile(TEXT("input.txt"), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
Mark Ransom
Hehe, nice demonstration of how the coding style is a bottomless source of bugs.
Hans Passant