C ++ file read/write

Source: Internet
Author: User

 

Http://stlchina.huhoo.net/bin/view.pl/Main/STLDetailString

 

Add # include
<Fstream>

Using namespace STD;

View code

1 // Ofstream myfile ("C: \ 1.txt", IOS: Out | IOs: trunc );
2 //
3 // Myfile <"China" <Endl <"Net" <"wgk ";
4 // Myfile. Close ();
5
6 Ifstream mfile1;
7 Mfile1.open ( " C: \ 1.txt " , IOS :: In );
8 If (! Mfile1) {cout < " File Error " ;}
9 Else
10 {
11 Char Ch;
12 String Content;
13 While (Mfile1. Get (CH ))
14 {
15 Content + = CH;
16 Cout <ch <Endl;
17 }
18 Mfile1.close ();
19 Cout <content <Endl;
20 }

C ++ file stream:
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. The content is as follows:
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: \ myfiles \ readme.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); // use the open function 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.
Use read/write to perform read/write operations, instead of 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
# 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
# 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 '\ 0'
# 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, '\ 0 ')! = 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
# 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.