C ++ read/write file stream instance program description

Source: Internet
Author: User

C ++ read/write file stream instance program description

This article describes how to read and write file stream instances in c ++.

Methods for reading and writing text files

Read and Write binary files

 

C ++ file stream:

 

 

Copy the Code as follows:

Fstream // file stream

Ifstream // input file stream

Ofstream // output file stream

 

// Create a text file and write information

// Output the information to the file in the same way as the output information on the screen.

# Include <iomanip. h>

# Include <fstream. h>

Void main ()

{

Ofstream f1 ("d: me.txt"); // open the file for writing. If the file does not exist, create it.

If (! F1) return; // stops running if the file fails to be opened.

F1 <setw (20) <"name:" <"Lian Dongfang" <endl; // use the insert operator to Write File Content

F1 <setw (20) <"Home Address:" <"Henan Zhengzhou" <endl;

F1.close (); // close the file

}

 

 

Open the file d: me.txt after running, whose content is: Name: Lian Dongfang Home Address: Zhengzhou, Henan Province

 

File Operations:

Open a file

File Name

Note that the slash in the path name must be double-written, for example, "D: MyFilesReadMe.txt"

File Opening Option:

Ios: in = 0x01, // for reading. If the file does not exist, create it (ifstream is enabled by default)

Ios: out = 0x02, // for writing. If the file does not exist, it is created. If the file already exists, the original content is cleared (default open mode for ofstream)

Ios: ate = 0x04, // when the file is opened, the pointer is at the end of the file. The position of the pointer can be changed. It is often used together with in and out.

Ios: app = 0x08, // for writing. If the file does not exist, it is created. If the file already exists, it is written to the new content after the original file content, and the pointer position is always at the end.

Ios: trunc = 0x10, // cut the file length to 0 before reading and writing (default)

Ios: nocreate = 0x20, // an error occurs when the file does not exist. It is often used together with in or app.

Ios: noreplace = 0x40, // an error occurs when a file exists. It is often used in combination with out.

Ios: binary = 0x80 // binary format file

File Protection option:

Filebuf: openprot; // default compatible Sharing Mode

Filebuf: sh_none; // exclusive, not shared

Filebuf: sh_read; // read sharing

Filebuf: sh_write; // write sharing

How to open a file

Specify the file name and open mode when calling the constructor.

Ifstream f ("d: 12.txt", ios: nocreate); // by default, the file is opened in ios: in mode. If the file does not exist, the operation fails.

Ofstream f ("d: 12.txt"); // by default, the file is opened in ios: out mode.

Fstream f ("d: 12.dat", ios: in | ios: out | ios: binary); // open a binary file in read/write mode.

Use Open member functions

Fstream f;

F. open ("d: 12.txt", ios: out); // The open function is used to operate multiple files using the same object.

Check whether it is enabled successfully

Successful:

If (f) {...} // available to ifstream and ofstream objects, fstream objects are unavailable.

If (f. good ()){...}

Failed:

If (! F ){...}//! The operator has been overloaded.

If (f. fail ()){...}

Read/write operations

Use the <,> Operator

Only read/write operations on text files can be performed. errors may occur when binary files are used.

Use Function members such as get, put, read, and write

The common function used with read is gcount (), which is used to obtain the actual number of bytes read.

Precautions for reading and writing binary files

Ios: binary must be specified in the open mode; otherwise, an error occurs during read/write operations.

You can use readwrite to perform read and write operations without using the insert or extract operators. Otherwise, an error occurs.

Use the eof () function to check whether the file has been read. Use gcount () to obtain the actual number of bytes read.

Close file

Use the member function close, for example:

F. close ();

Using destructor

When the end of the object life cycle, the system checks whether the object is closed and closes the file that is not closed.

Random file read/write

By moving the file read/write pointer, you can read and write the object at the specified position.

Seekg (absolute position); // absolute movement, // input stream operation

Seekg (relative position, reference position); // relative operation

Tellg (); // returns the current pointer position

Seekp (absolute position); // absolute movement, // output stream operation

Seekp (relative position, reference position); // relative operation

Tellp (); // returns the current pointer position

Reference location:

Ios: beg = 0 // relative to the file header

Ios: cur = 1 // relative to the current location

Ios: end = 2 // relative to the end of the file

Example of reading/writing a text file

/To correctly read the data written into the file, it is best to separate the data

 

 

Copy the Code as follows:

# Include <fstream. h>

Void main ()

{

Fstream f ("d: try.txt", ios: out );

F <1234 <''<3.14 <'A' <" How are you "; // write data

F. close ();

F. open ("d: try.txt", ios: in );

Int I;

Double d;

Char c;

Char s [20];

F> I> d> c; // read data

F. getline (s, 20 );

Cout <I <endl; // display data

Cout <d <endl;

Cout <c <endl;

Cout <s <endl;

F. close ();

}

 

 

Running result:

 

1234

3.14

A

How are you

Press any key to continue

 

Display text file content

 

Use get () to read one character at a time ---------------------------- solution 1

 

 

Copy the Code as follows:

# Include <fstream. h>

Void main ()

{

Ifstream fin ("d: .txt", ios: nocreate );

If (! Fin ){

Cout <"File open error! N ";

Return;

}

Char c;

While (c = fin. get ())! = EOF) cout <c; // pay attention to the judgment of the end Condition

Fin. close ();

}

 

// Use get (char *, int n, char delim = 'n') to read multiple characters at a time ---- solution 2

// Cleverly read text files without the character''

# Include <fstream. h>

Void main ()

{

Ifstream fin ("d: .txt", ios: nocreate );

If (! Fin ){

Cout <"File open error! N ";

Return;

}

Char c [80];

While (fin. get (c, 80 ,'')! = NULL) cout <c; // pay attention to the judgment of the end Condition

Fin. close ();

}

// Use read (char *, int n) to read the file --------------------------- solution 3

# Include <fstream. h>

Void main ()

{

Ifstream fin ("d: .txt", ios: nocreate );

If (! Fin ){

Cout <"File open error! N ";

Return;

}

Char c [80];

While (! Fin. eof () // determines whether the file has been read.

{

Fin. read (c, 80 );

Cout. write (c, fin. gcount ());

}

Fin. close ();

}

 

 

 

Copy an object

Binary File Operation example

 

 

Copy the Code as follows:

# Include <fstream. h>

Void main ()

{

Ifstream fin ("C: 1.exe", ios: nocreate | ios: binary );

If (! Fin ){

Cout <"File open error! N ";

Return;

}

Ofstream fout ("C: 2.exe", ios: binary );

Char c [1024];

While (! Fin. eof ())

{

Fin. read (c, 1024 );

Fout. write (c, fin. gcount ());

}

Fin. close ();

Fout. close ();

Cout <"Copy over! N ";

}

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.