C ++ learning notes: input, output, and files

Source: Internet
Author: User

C ++ learning notes: input, output, and files
1. The concept of stream data is moved from one address in the memory to another. It is called data flow. stream operation flow is implemented through the buffer mechanism. Buffer: an area of memory-used for data exchange between files and memory. Read data from the file: file → buffer → memory write data to the file: memory → buffer → why does the file use a buffer instead of directly reading data from the file to the memory or directly writing data into the file? Our files are usually stored on disks. Reading a character from a disk requires a lot of hardware activity, which is very slow. The buffer method reads a large amount of information from the disk, stores the information in the buffer, and then reads a byte from the buffer each time, because reading a single byte from the memory is much faster than reading from the hard disk, this method is faster and more convenient. After talking about this, you only need to know that the buffer method is more efficient. Ii. stream library describes the input and output class libraries created using the inherited methods, including two parallel basic classes: streambuf and ios, all stream classes use one of the two as the base classes. The streambuf class provides low-level operations on the buffer zone: It sets the buffer zone, operates on the buffer pointer, and provides the user with the stream class interfaces for ios and Its Derived classes such as buffer access characters. This article mainly introduces ios, because ios is almost a required class in programming, streambuf classes are rarely used directly. The following picture comes from the Network: 3. File opening and closing when file operations are performed in the program, the header file "fstream" should be added. To open the file and perform corresponding operations, the corresponding Stream object must be defined. For example: ifstream in; // file input stream object, ofstream out; // file output stream object, fstream both; // file input/output stream object file open using the member function open (); the first parameter of the prototype void (const char * s, ios_base: openmode, mode = ios_base: out | ios_base: trunc) indicates the path to open the file, the second parameter indicates the file opening method, and the third parameter indicates the access method. It indicates ios: ate to open the file and move it to the end of the file. ios: app appends the file to ios: in is used as the input file (ifstream default) ios: out is used as the output file (ofstream default) ios: trunc if the file exists, clear the file content (default) ios :: if the file does not exist in nocreate, the system returns the error ios: noreplace. If the file exists, the system returns the error ios: binary Method 1: first define a file stream object, and then call the member function open () to open a file. For example, 1 ifstream f1; // define the input stream object f12 f1.open ("d: \ vcprg \ 7-3.cpp"); // open the vcprg folder (directory) of the d Drive) method 2: Use the constructor to open a file when defining a file stream object. For example, ifstream f1 ("d: \ vcprg \ 7-3.cpp") indicates the opened file after opening the file with a file stream object. Copy code 1 # include <iostream> 2 # include <fstream> 3 4 using namespace std; 5 6 void main (void) 7 {8 ifstream f1; // define the file input stream object 9 f1.open ("d: \ vcprg \ 7-3.cpp"); // open the file 10 char c; 11 while (! F1.eof () // It indicates that the file is not over and the loop is triggered. eof () returns true12 {13 f1.get (c); 14 cout <c; 15} 16 cout <endl; 17 f1.close (); // close file 18} copy the code file access method: When ifstream is used to define a stream object and open a file, the default value is ios_base: in. When you use ofstream to define a stream object and open a file, the default value is ios_base: out. When you use fstream to define a stream object and open a file, the open mode should be provided (the file can be opened in multiple ways using bitwise OR operations) such as: 1 fstream f; 2 f. open ("file. cpp ", ios_base: in | ios_base: out). For example, copy the 7-3.cpp file under the ddisk vcprg folder (directory) to the text.txt file. Copy code 1 # include <iostream> 2 # include <fstream> 3 4 using namespace std; 5 6 void main (void) 7 {8 ifstream f1; // define the file input stream object 9 ofstream f2; 10 f1.open ("d :\\ vcprg \ 7-3.cpp"); // open the file 11 f2.open ("d: \ vcprg \ text.txt "); // open the file 12 char c in write mode; 13 while (! F1.eof () // It indicates that the file is not over. eof () returns true14 {15 f1.get (c); 16 f2 <c; 17} 18 cout <"file copied successfully" <endl; 19 f1.close (); // close file 20 f2.close (); 21} copy code file exception handling: when opening a file may fail, an exception handler should be added to the program. (1) Use a Condition Statement to determine whether the file flow flag failbit is true. If (! File Stream object) {<exception handler >}if (file stream object) {<normal handler >}( the 13 rows in the preceding example use this method) (2) use the member fail () function if (file stream object. fail () {<exception handler >}if (! File Stream object. fail () {<normal processing program >}( 3) use the member function good () if (! File Stream object. good () {<exception handler >}if (file stream object. good () {<normal processing program>} (4) the newer C ++ implementation provides a better method of is_open (). We recommend using this method, however, the old-fashioned C ++ does not implement this method, and the above three methods can be used to close files: Format: file stream object. close (); close the file operation includes writing the buffer data to the file completely, adding the end mark of the file, and cutting off the connection between the stream object and the external file. If the lifetime of the stream object is not over, it can be reused. When the lifetime of a stream object ends, the system will automatically close the file, for example, copy code 1 ofstream ofile; // create output file stream 2 3 ofile. open ("myfile1"); // The ofile stream is associated with the file "myfile1" 4 5 ...... // Access the file "myfile1" 6 7 ofile. close (); // close the file "myfile1" 8 9 ofile. open ("myfile2"); // reuse ofile stream copy Code 4. read/write of file read/write of text files: Methods get (char &) and get () provides the single-character input function without skipping white spaces; The put (char &) and put () methods provide the single-character output function without skipping white spaces; The get (char *, int, char) Function) getline (char *, int, char) and getline (char *, int, char) read the entire row by default. Binary file read/write: The read/write functions of binary files are read () and write () respectively (). Write binary file format, output file stream object. write (char *) & object or & object array name [subscript], sizeof (Object Name or Class Name); read binary file format, input file stream object. read (char *) & object or & object array name [subscript], sizeof (Object Name or Class Name); use format control (for details about format control, refer to encoding) create a text file: Copy code 1 # include <fstream> 2 # include <iomanip> 3 4 using namespace std; 5 6 7 int main () 8 {9 ofstream ost; 10 ost. open ("d :\\ my2.dat"); 11 ost <"1234567890" <endl; 12 int a = 123; 13 ost <a <endl; 14 ost <setw (10) <a <endl; 15 ost <resetiosflags (ios: right) <setiosflags (ios: left) 16 <setfill ('#') <setw (10) <a <endl; 17 ost <resetiosflags (ios :: left) <setiosflags (ios: right) 18 <setprecision (5) <setw (10) <12.34567890 <endl; 19 ost. close (); 20 return 0; 21} copy the code to create a text file containing the student ID, name, and score: copy the Code 1 # include <I Ostream> 2 # include <fstream> 3 # include <cstdlib> 4 5 using namespace std; 6 7 int main () 8 {9 char fileName [30], name [30]; 10 int number, score; 11 12 ofstream outstuf; // create the output stream object 13 14 cout <"Please input the name of students file: \ n "; 15 cin> fileName; // enter the file name 16 17 outstuf. open (fileName, ios: out); // open the file 18 19 if (! Outstuf) 20 {21 cerr <"File cocould not be open. "<endl; 22 exit (1); 23} 24 outstuf <" Student Achievement file \ n "; 25 cout <" Input the number, name, and score: (Enter Ctrl-Z to end input) \ n? "; // In windows, Ctrl-Z ends Input and Output 26 27 while (cin> number> name> score) 28 {29 outstuf <number <''<name <'' <score <'\ n'; 30 cout <"? "; 31} 32 outstuf. close (); 33 return 0; 34} copy the code binary file, figure 5 from a school tutorial. Summary The istream class defines multiple versions of the extraction operator (>) to identify all basic C ++ types, and convert character input to these types. The get () method family and the getline () method provide further support for single-Character Input and string input. The ostream class defines multiple versions of the insert operator (> ), identifies all basic C ++ types and converts character input to these types of output. The put () method provides further support for single-Character Input and string input; The ios_base class method and the controllers defined in the file iostream and iomanip (refer to the http://wonderow.cnblogs.com/archive/2005/06/21/178719.html) can control formatting output; to operate a file, you must associate the file with the stream. You can use all istream methods to read the file and use the ofstream object to associate the file, you can use the ofstream method to write files. If you use the fstream object to associate files, you can use the fstream Input and Output Methods for files. To associate files with streams, you must first create a file stream object, then, use the open () method to associate the stream with the file, and close () method to terminate the association between the stream and the file. Text Files store information in character format, for example, numeric values are converted to character representation; seekg () and seekp () provide random access to files through pointers. The tellg () and tellp () Methods report the location of the current file;

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.