简体   繁体   中英

How can I tell the program to stop using freopen

I am beginner in C++ and I have a question that is beyond my limits. I compile under GNU GCC. I use

#include<stdio.h>

also known as:

#include<cstdio>

At some point in my program I tell the program to use the file de_facut.txt as an in file:

freopen("de_facut.txt","r",stdin);

How can I tell the program to use the console to put the input (as default) instead of the in file? First I want to read from that file, but later in the program I want the user to enter input in the console. I hope you understood my problem, I am not very good at english.

The same question has been asked about stdout : How to redirect the output back to the screen after freopen("out.txt", "a", stdout) , but the answer is the same for both - there's no clean way of doing this : http://c-faq.com/stdio/undofreopen.html

Since you do need to read from the console later in the program, I'd suggest you just open the file as, well, a file. If the reason you wanted to use stdin to read from a file is the convenience of not having to pass the file handle to functions like fscanf , you could consider using fstream facilities instead - the code can look exactly as when reading from the console:

#include <iostream>
#include <fstream>

using namespace std;
int main()
{
    int x;
    cin >> x; // reading from console
    {
        ifstream cin("input.txt");
        cin >> x; // reading from file
    }
    cin >> x; // again from console

    return 0;
}

Use fclose() :

FILE *fp=freopen("data.txt","r",stdin);
/*your code here*/
fclose(fp);

ref: C library function - freopen()

In windows,

freopen("CON","r",stdin);

this code worked for me. It switches the stdin to console.
PS: The text file used to take input before this, must be ended with a newline.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM