質問

Visual C++ is reporting that an invalid parameter was passed to fclose, that parameter being the FILE* returned by freopen_s:

#include <WinSock2.h>
#include <iostream>

int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow) {
    UNREFERENCED_PARAMETER(hPrevInstance);
    UNREFERENCED_PARAMETER(nCmdShow);

#ifdef _DEBUG
    AllocConsole();
#else
    AttachConsole(ATTACH_PARENT_PROCESS);
#endif

    FILE* pCout;
    freopen_s(&pCout, "conout$", "w", stdout); //returns 0

    fclose(pCout);

#ifdef _DEBUG
    system("pause");
#endif

    FreeConsole();

    return 0;
}

Should I not attempt to close conout$ at the end of the program? Is the exception being thrown because the file pointer is shared between processes for all console output?

役に立ちましたか?

解決

The call to fclose is failing because you are passing a null FILE*. The FILE* is null because the call to freopen_s fails. That call fails because the process has no console to be opened.

Your program works in debug builds because you call AllocConsole to allocate a console for your process. Your program does not work in release builds because you do not call AllocConsole; you call AttachConsole, which will fail (and have no effect) if the parent process has no console.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top