Search code examples
cstdin

How to change stdin back to reading from terminal after using "freopen" (in C)?


I used freopen to redirect stdin to reading from a file, and it worked perfectly

FILE *fp = freopen(args[index + 1], "r", stdin);
        if(fp == NULL){
            printf("file not found\n");
            return 1;
        }

After that I do some processing and want to go back to reading from the terminal, but I can’t seem to figure out how to do that.

I'm closing the file using fclose

fclose(fp);

I tried closing stdin too but it didn’t make a difference.

fclose(stdin);

I tried to

int savedStdIn = dup(0);

before freopen, and

dup2(savedStdIn, 0);

at the end of the code (along with fclose(fp)) but that didn’t work too.


Solution

  • You are very close:

    // before reopen
    int savedStdIn = dup(fileno(Stdin));
    freopen(...) ;
    ...
    // restore stdin
    fclose(Stdin) ;
    stdin = fdopen(savedStdIn, “r”)
    ...
    

    In theory, close/dup approach can work, provided you flush the buffers. This is risky, and implementation dependent, as it attempt to bypass the studio library calls by accessing system calls.

    // before reopen
    int savedStdIn = dup(fileno(Stdin));
    freopen(...) ;
    ...
    // restore stdin
    fflush(stdin):
    Dup2(SavedstdIn), fileno(stdin))