samedi 23 janvier 2016

fgetwc EOF loop test fails, but 65535 OK

VS10 & MCBS:

For this I have created a file called c:\eoftest containing the text "test". The value of ch on the 5th pass in the following code is 65535 returned by fgetwc, but it does not equate to EOF, which we all know is defined in stdio.h as (-1):

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

int main()
{
    int ch;
    FILE *stream = NULL;
    wchar_t buf[5];
    memset (buf, '\0', sizeof(buf));
    stream = _wfopen(L"C:\\eoftest.txt", L"r");

            for (int i = 0; (i  < (sizeof(buf) - 1) && ((ch = fgetwc(stream)) != EOF) && (ch != '\0')); i++) //we are reading so last null condition mandatory
            {
            ungetwc(ch, stream);
            buf[i] = (wchar_t)(ch = fgetwc(stream));
            }
}

Replacing the condition (sic) with (ch = fgetwc(stream)) != 665535) works in this case, but what is not done here to ensure the EOF test can succeed?

Aucun commentaire:

Enregistrer un commentaire