Use the C language redirection function freopen to exchange two text files

Source: Internet
Author: User
/*** Autor: wangzhicheng *** E-mail: 2363702560@qq.com ** Date: 2012/10/4 ** description: swap two files */# include <iostream> # include <cstdlib> # include <cstdio> # include <string> using namespace STD; /* write the source file to the target file */inline static bool writetofile (string srcfilename, string desfilename) {file * stream; stream = freopen (srcfilename. c_str (), "r", stdin); // redirects the content of the source file to the standard input stream/*, which means that the standard input stream points to the file srcfilename. Reading the standard input stream is actually for srcfilena Me read */If (! Stream) return false; stream = freopen (desfilename. c_str (), "W", stdout); // redirects the content of the target file to the standard output stream./* this means that the standard output stream points to the file desfilename, writing to the standard output stream is actually writing to desfilename */If (! Stream) return false; char C; while (scanf ("% C", & C )! = EOF) printf ("% C", c); // read characters from the input stream, and then write to the output stream/* which means to read content from the source file, then write the target file */fclose (stdin); fclose (stdout); Return true;} inline static void swapfile (string & filename1, string & filename2) {string tmpfilename = "E: \ tmp.txt "; // specify the temporary file name cout <" Enter the first file name (full path): "; CIN> filename1; cout <"enter the second file name (full path):"; CIN> filename2; If (! Writetofile (filename1, tmpfilename) return; If (! Writetofile (filename2, filename1) return; If (! Writetofile (tmpfilename, filename2) return; cout <"file exchange successful! "<Endl;} void main () {cout <" written by wangzhicheng! "<Endl; string filename1, filename2; swapfile (filename1, filename2 );}

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.