Usage of freopen Function

Source: Internet
Author: User

 

The file opening function used this time is no longer fopen, but another function freopen contained in stdio. h.

 
File*Freopen( Const Char *Filename, Const Char *Mode,File*Stream);

[Parameter description]

Filename: name of the file to be opened

Mode: the mode in which the file is opened, which is the same as the mode in fopen (R/W ).

Stream: file pointer, usually using standard stream files (stdin/stdout/stderr)

[Usage]

Because the file pointer uses a standard stream file, we can not define the file pointer.

Next, use the freopen () function to open the input file slyar. In in read-only mode R (read ).

 
Freopen("Slyar. In", "R",Stdin);

Then use the freopen () function to open the output file slyar. Out in write mode W (write ).

 
Freopen("Slyar. Out", "W",Stdout);

The next thing is the advantage of using the freopen () function. We do not need to modify scanf and printf, but maintainCode. Because the freopen () function redirects the standard stream and points it to the previously specified file, saving time and effort. Like...

Finally, you only need to use fclose to close the input and output files.

 
Fclose(Stdin);
 
Fclose(Stdout);

To restore the handle, you can re-open the standard console device file, but the name of the device file is related to the operating system.

DOS/win:

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

Linux:

Freopen("/Dev/console", "R",Stdin);

Add a code template:

# Include < Stdio. h >

Int Main ()
{
Freopen ( " Slyar. In " , " R " , Stdin );
Freopen ( " Slyar. Out " , " W " , Stdout );

/**/ /*Write code as is in the middle, and do not need to modify anything*/

Fclose (stdin );
Fclose (stdout );
Return   0 ;
}

PS. one problem just found is that when compiling the source code containing file operations with C-free, you must put fopen or freopen under the definition of all variables; otherwise, the compilation will be wrong... bytes

From: http://www.slyar.com/blog/c-freopen-stdin-stdout.html

 

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.