1
\$\begingroup\$

Here is the book question:

Modify the CatFile function in the program so that it uses WriteConsole rather than WriteFile when the standard output handle is associated with a console.

And here is my solution:

static VOID CatFile(HANDLE hInFile, HANDLE hOutFile)
{
    DWORD nIn, nOut;
    TCHAR buffer[BUF_SIZE];
    LPTSTR pBuffer = &buffer[0];

    while (ReadFile(hInFile, buffer, BUF_SIZE, &nIn, NULL) &&
        (nIn != 0) &&
        (WriteFile(hOutFile, buffer, nIn, &nOut, NULL) || WriteConsole(hOutFile, pBuffer, _tcslen(pBuffer), &nOut, NULL)));
    return;
}

The part from the || sign in the code above is my addition to the code.

My question is to know if that would work once WriteFile wouldn't be TRUE since hOutFile is a handle of a console?

Another part of the question is just about the WriteConsole function: are these the correct arguments?

\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

No comment on what your call as I don't know what WriteFile() or WriteConsole() do.

But that is seriously abusing the && and !! operators.
I don't think I would ever let that code pass a review:

while (ReadFile(hInFile, buffer, BUF_SIZE, &nIn, NULL) &&
    (nIn != 0) &&
    (WriteFile(hOutFile, buffer, nIn, &nOut, NULL) || WriteConsole(hOutFile, pBuffer, _tcslen(pBuffer), &nOut, NULL)));

// Why not write it like this:

// While we manage to read a good value:
while (ReadFile(hInFile, buffer, BUF_SIZE, &nIn, NULL) && (nIn != 0))
{
     if (!(   (WriteFile(hOutFile, buffer, nIn, &nOut, NULL))
          || (WriteConsole(hOutFile, pBuffer, _tcslen(pBuffer), &nOut, NULL))
          )
        )
     {
          // Write Error
          break;
     }
}
// Now check for read errors to report.
\$\endgroup\$
0
\$\begingroup\$

From a quick thought - Shouldn't WriteFile actually work when hOutFile is the console?

Otherwise I guess that you may need to check whether GetStdHandle(...) == hOutFile.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.