1> in the C language, we all know how to input the TXT file directly and output the output to the file. The wording is simple:
Freopen ("Input.txt", "R", stdin); Freopen ("Output.txt", "w", stdout);
is to tune a common function
Freopen, in the header file <stdio.h>, this function has three parameters, the first is the file name of the read or output file, the second has two optional parameters, "W" means write, that is written, "R" means read, the mark reads into, and then the last is a fixed usage, StdIn means reading, and the stdout is a fixed, no change, so just remember the fixed structure.
2> Let's take a look at the operations file in C + +, first we look at writing the file.
A) It contains a class,Ofstream, in the header file <fstream>, cout is a variable derived from this class, so cout usage can be used for this class, but it is directly used to output to the file.
Let's take a look at an exercise:
#include <iostream> #include <fstream>using namespace Std;int main () { ofstream outfile,fout; Outfile.open ("Fish.txt"); Char s[50]; cin>>s; cout << fixed; Cout.precision (2); COUT.SETF (ios_base::showpoint); cout<< "Make and Model:" <<s<<endl; outfile<< "PPS Make and Model:" <<s<<endl; Writes the output to a file, all cout functions can be outfile.close (); return 0;}
After running, you can find fish.txt this file, that is, outfile this variable output content.
B) The use of read-in files is also very simple, using the class Ifstream, also in the header file <fstream>, cin is a variable derived from it, so all the use of CIN can also be used in this class.
Let's look at an exercise:
#include <iostream> #include <fstream> #include <cstdlib>using namespace Std;int main () { Ifstream infile; Infile.open ("Fish.txt"); if (!infile.is_open ()) { cout<< "Could not open File!!!"; Exit (exit_failure); } Double val,sum = 0.0; int count = 0; InFile >> Val; while (Infile.good ()) { count++; Sum+=val; InFile >> val; } if (infile.eof ()) cout<< "End of file!!"; cout<< "Count:" <<count<<endl; cout<< "Sum:" <<sum<<endl; Infile.close (); return 0;}
This program is a bit cumbersome to write, he checks whether the file opened successfully, and whether to end with EOF, but the file read in is very concise.
First run this program must build a Fish.txt file, which put some floating point, separated by a space, you can run a look at the results.
Access files are similar to this:
18 19 18.5 13.5 14 17.5
16 19.5 20 18 12 18.5
Everyone can try.
Reading and writing of files in C + +