C + + Standard IO redirection

Source: Internet
Author: User

This is very useful for OJ on the topic. OJ is basically the standard input output (except for Usaco). But if you're typing from the console while you're debugging, it's a waste of precious time. We can redirect the standard input, debug the time from the file to read, commit to read from the standard input.

In the C language, the method is relatively simple. Use function Freopen ():

    1. Freopen ("data.in","R", stdin);
    2. Freopen ("Data.out","W", stdout);

This redirects the standard input to the data.in file, and the standard output is redirected to the Data.out file.

After these two lines of code, the SCANF function is read from the data.in file, and the printf function is output to the Data.out file.

In C + +, there are two overloaded functions for convection redirection:

    1. streambuf* rdbuf () const;
    2. streambuf* rdbuf (STREAMBUF *)

is equivalent to the Get/set method.

    1. Streambuf *backup;
    2. Ifstream fin;
    3. Fin.open ("data.in");
    4. Backup = Cin.rdbuf (); //Back up CIN ' s streambuf
    5. Cin.rdbuf (Fin.rdbuf ()); //Assign file ' s streambuf to CIN
    6. ... cin would read from file
    7. Cin.rdbuf (Backup); //Restore CIN ' s original Streambuf

Note that in the end we used Cin.rdbuf (backup) to redirect Cin back to the console.

However, it is less elegant to implement the same functionality in C.

Because the name of the standard console device file is associated with the operating system.

In Dos/windows, the name is con.

Freopen ("Con", "R", stdin);

In Linux, the console device is/dev/console

Freopen ("/dev/console", "R", stdin);

In addition, in Unix-like systems, the DUP system can also be used to pre-replicate a copy of the original stdin handle.

C + + Standard IO redirection

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.