C + + file input and output

Source: Internet
Author: User

1. Introduction of header File FStream
The FStream header file defines the class Ifstream and file output classes used for file input Ofstream

2. Writing files
1) Create a Ofstream object to manage the output stream
2) Associate the object with a file
3) Use this object in cout mode, the only difference is that the output will go to the file, not the screen.
4) Close the connection to the file
Examples are as follows:

ofstream Fout;fout.open ("test.txt"); Fout<<"  Write something"; Fout.close ();

creating objects and associated files can be combined into one step using constructors , which is equivalent to:

Ofstream fout ("test.txt"); Fout<<"write something  "; Fout.close ();

3. Read the file
1) Create a Ifstream object to manage the input stream
2) Associate the object with a file
3) Read the file using the Ifstream method
4) Close the connection to the file
Examples are as follows:

 ifstream fin ( test.txt   "  char   Ch;fin  >>ch; //  read a character from a file  char  buf[80  ];fin  >>buf; //  fin.getline (buf,80 ); //  read a line from a file  string   Line;getline (fin,line);  //  reads a row into a string  fin.close (); 

4. Read and write buffers
FStream Flow Management Objects are interacted with by buffers and files when they are read or written using the cout or Cin method.
Instead of reading or writing the file byte-by-bit.

About the close () function, when a stream object expires (such as a program termination), the connection to the file is automatically closed,
You can also use the Cose () display to close the connection. When the connection is closed, the buffer is flushed .

After the connection to the file is closed, the stream is not deleted, and the FStream stream object and its managed buffers still exist,
The stream can be reconnected to a file.

5. A simple read-write file example

#include <iostream>#include<fstream>#include<string>using namespacestd;Const stringFilename="Test.txt";intMain () {Ofstream fout (filename.c_str ());if(!Fout.is_open ()) {Cerr<<"Unable to open file"<<filename<<Endl;exit (0);} cout<<"Enter Password:";floatsecret;cin>>Secret;fout<<secret<<endl;fout.close (); Ifstream fin (Filename.c_str ());if(!Fin.is_open ()) {Cerr<<"Unable to open file"<<filename<<Endl;exit (0);} cout<<"the password entered is: \ n";Charch; while(Fin.Get(CH)) cout<<ch;fin.close ();return 0;}

The Is_open () function in the program is used to check if the file is open
The state of a stream object includes:
All smooth, has reached the end of the file, I/O operation failed and so on. If all goes well, the stream status is set to 0, otherwise set to 1.

6. Open multiple Files
1) You need to open multiple files at the same time, you need to create a stream for each file.
2) to open a set of files in turn, you can open only one stream and associate it to each file in turn.

As shown in the following example:

ifstream fin;fin.open ("test.txt"); Fin.close (); Fin.clear (); Fin.open (  "test2.txt"); Fin.close ();

7. File mode

Constant Meaning
Ios_base::in Open the file to read
Ios_base::out Open the file for writing
Ios_base::ate Open the file and move to the end of the file, the difference is that the latter can only be written at the end of the file, the former simply initializes the write pointer at the end of the file Ios_base::app
Ios_base::app Append to end of file
Ios_base::trunc If the file exists, clear the contents of the file
Ios_base::binary binary files

For Ifstream Open (), the default mode is Ios_base::in
For Ofstream Open (), the default mode is Ios_base::out|ios_base::trunc, open and empty the file

8. Binary Mode ios_base::binary

There are two kinds of storage types for files, text format or binary format .
The text format is easy to read, while the binary format is more precise, takes up little space, and reads faster.
Write operation:

Fout.write ((char*) &t,sizeof T);

Read operation:

Fin.read ((char*) &t,sizeof T);

Note the type instance address needs to be cast to the char* type.

9. Random Access

Random access means that the read-write pointer moves directly to any location in the file.

Jump function:

IStream & SEEKG (Streamoff,ios_base::seekdir); // relative address IStream & SEEKG (Streampos); // Absolute Address

The first method means that the position of the file is specified from the Seekdir parameter, and the location of the Streamoff.
Where the Streamoff unit is byte, Seekdir represents three positions of the file (top Ios_base::beg, bottom ios_base::end, current position ios_base::cur)

The second method means that the position is streampos from the beginning of the file.
Streampos represents the absolute position in the file, in bytes

SEEKG ()
Move to the beginning of a file

TELLG ()
Returns the current position of the read-write pointer

Below, we write a simple random access example using the binary file mode:

#include <iostream>#include<fstream>#include<iomanip>Const intlim= -;structplanet{CharName[lim]; Doublepopulation; Doubleg;};Const Char*file ="Planets.dat"; inlinevoidEatline () { while(Std::cin.Get()!='\ n')Continue;}intMain () {using namespacestd;    Planet Pl; cout<<fixed;    FStream finout; Finout.open (file,ios_base::inch|ios_base:: out|ios_base::binary); intCT =0; if(Finout.is_open ()) {FINOUT.SEEKG (0); cout<<"contents of File"<<file<<Endl;  while(Finout.read (Char*) &AMP;PL,sizeofPL)) {cout<<ct++<<":"&LT;&LT;SETW ( -) <<pl.name<<":"<<setprecision (0) &LT;&LT;SETW ( A) <<pl.population<<setprecision (2) &LT;&LT;SETW (6) <<pl.g<<Endl; }        if(finout.eof ()) finout.clear (); Else{Cerr<<"Unable to open file"<<file<<Endl; Exit (0); }    }    Else{Cerr<<"Unable to open file"<<file<<Endl; Exit (0); } cout<<"Enter record number to change:"; LongRec; CIN>>Rec;    Eatline (); if(rec<0|| rec>=CT) {Cerr<<"Invalid index number"<<Endl; Exit (0); } Streampos Place= rec*sizeofPL;    FINOUT.SEEKG (place); if(Finout.fail ()) {Cerr<<"index number cannot be found"<<Endl; Exit (0); } finout.read ((Char*) &AMP;PL,sizeofPL); cout<<"index number found"<<Endl; cout<<rec<<":"&LT;&LT;SETW ( -) <<pl.name<<":"<<setprecision (0) &LT;&LT;SETW ( A) <<pl.population<<setprecision (2) &LT;&LT;SETW (6) <<pl.g<<Endl; if(finout.eof ()) finout.clear (); cout<<"Enter Name:"; Cin.Get(Pl.name,lim);    Eatline (); cout<<"Population:"; CIN>>pl.population; cout<<"g:"; CIN>>PL.G;    FINOUT.SEEKP (place); Finout.write ((Char*) &AMP;PL,sizeofPL) <<Flush; if(Finout.fail ()) {Cerr<<"Write failed index number"<<Endl; Exit (0); } CT=0; FINOUT.SEEKG (0); cout<<"contents of File"<<file<<Endl;  while(Finout.read (Char*) &AMP;PL,sizeofPL)) {cout<<ct++<<":"&LT;&LT;SETW ( -) <<pl.name<<":"<<setprecision (0) &LT;&LT;SETW ( A) <<pl.population<<setprecision (2) &LT;&LT;SETW (6) <<pl.g<<Endl;    } finout.close (); cout<<"done.\n"; return 0;}

program, we used a special flow management object FStream,
FStream inherits Sub-iostream, while iostream inherits from IStream and Ostream
So FStream inherits two buffers, one for input and one for output
and can synchronize the processing of two buffers. That is, the position of the input pointer and the output pointer are always the same.
This allows you to read and write at the same time by using a single stream to manage objects.

Reference: "C + + primer.plus" pp.768-788

C + + file input and output

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.