Converting a FILE* to a HANDLE ? - Programmer

This is a discussion on Converting a FILE* to a HANDLE ? - Programmer ; I have a program that has code that outputs text to both STD_OUTPUT_HANDLE and to the stdout FILE*. I want to redirect both of these to the same file log file. If I use SetStdHandle() to redirect STD_OUTPUT_HANDLE to go ...

+ Reply to Thread
Results 1 to 2 of 2

Thread: Converting a FILE* to a HANDLE ?

  1. Converting a FILE* to a HANDLE ?

    I have a program that has code that outputs text to both
    STD_OUTPUT_HANDLE and to the stdout FILE*. I want to redirect
    both of these to the same file log file.

    If I use SetStdHandle() to redirect STD_OUTPUT_HANDLE to go to
    a file, then output to stdout doesn't go there; if I use
    freopen() to redirect stdout, then output to STD_OUTPUT_HANDLE
    doesn't go there; if I do both, then output from both goes
    there, but the output is jumbled a little presumeably because
    the two buffers aren't synchronized.

    What I think would solve this would be to get a file HANDLE for
    a FILE*, i.e., convert the FILE* for stdout after being
    redirected using freopen() to a HANDLE, then pass that handle to
    SetStdHandle().

    Is this possible? Can I get a HANDLE from a FILE*? If not, how
    can I do what I want?

    - Paul

  2. Re: Converting a FILE* to a HANDLE ?

    Paul J. Lucas wrote:

    > I have a program that has code that outputs text to both
    > STD_OUTPUT_HANDLE and to the stdout FILE*. I want to redirect
    > both of these to the same file log file.


    > What I think would solve this would be to get a file HANDLE for
    > a FILE*, i.e., convert the FILE* for stdout after being
    > redirected using freopen() to a HANDLE, then pass that handle to
    > SetStdHandle().


    You can do it in two steps, use _fileno() to get the CRT file descriptor
    for the FILE stream and the _get_osfhandle() to get the HANDLE for the
    CRT file descriptor. After you have used freopen() to redirect stdout to
    the log file, try this:

    SetStdHandle((HANDLE) _get_osfhandle(_fileno(stdout)));

    --
    Olof Lagerkvist
    ICQ: 724451
    Web: http://here.is/olof


+ Reply to Thread