C + + file read and write operations

Source: Internet
Author: User

Read and write operation Flow:

1. Define a Stream object for the file to be manipulated.

2. Open (Create) the file.

3. Perform read and write operations.

4. Close the file.

Detailed

1. Create a Stream object:

Input file Stream Class (perform read operation): Ifstream in;

Output file Stream class (perform write operation): Ofstream out;

Input output file Stream class: FStream both;

Note: These three types of file stream classes are defined in FStream, so just add FStream to the header file.

2. Open the function using the member function:

How to use: Ios::in Open File as input (read operation)

Ios::out Open the file as output (write operation), if there is already a folder of this name, the original content of all clear

Ios::app opening a file as input, and writing data to the end of the file

Ios::ate open a file, move the file pointer to the end of the file

Ios::binary open a file in binary mode, default to text open mode

Example: Defining a Stream Class object: Ofstream out (output stream)

Write operation: Out.open ("Test.dat", ios::out); Open a question named Test.dat.

3. Read and write text files:

(1) write the string Hello world to the disk file Test.dat

      

#include <iostream>#include<fstream>using namespacestd;intMain () {Ofstream fout ("Test.dat"Ios:: out); if(!fout) {cout<<"File open failed! "<<Endl; Exit (1); } fout<<"Hello World";  Fout.close (); return 0; Checking the file Test.dat will find the contents of the file as Hello world

    

(2) Read the files in the Test.dat and display them on the screen.

#include <iostream>#include<fstream>using namespacestd;intMain () {ifstream fin ("Test.dat"Ios::inch); if(!Fin) {cout<<"File open failed! "<<Endl; Exit (1); }   Charstr[ -]; Fin.getline (str, -) cout<<str<<Endl;  Fin.close (); return 0; }                           

4. Closing the file:

Stream object. Close (); No parameters

C + + file read and write operations

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.