C + + read-write file Flow instance program to explain _c language

Source: Internet
Author: User

How to master the reading and writing of text files
Learn how to read and write binary files

C + + file Flow:

Copy Code code as follows:

FStream//File Flow
Ifstream//input file stream
Ofstream//Output file stream

Create a text file and write information
Output information to a file as if it were printed on the screen
#include <iomanip.h>
#include <fstream.h>
void Main ()
{
Ofstream F1 ("D:\\me.txt"); Open file for write, create it if file does not exist
if (!F1) return; Run if Open file fails
F1<<SETW << "Name:" << "Cheap Oriental" <<endl; Writing file contents using the Insert operator
F1<<SETW << "Home Address:" << "Henan Zhengzhou" <<endl;
F1.close (); Close File
}

After running, open file D:\me.txt, its contents such as: Name: cheap Oriental Home Address: Zhengzhou, Henan

File actions:
Open File
Filename
Note that the slash in the path name should be double written, such as "D:\\myfiles\\readme.txt"
File Open options:
Ios::in= 0x01,//for read, file not present create (ifstream default open mode)
Ios::out = 0x02,//write, File not present, create if file already exists, empty original content (ofstream default open mode)
Ios::ate = 0x04,//When the file is open, the pointer is at the end of the file. Can change the position of the pointer, often and in and out of the joint use
Ios::app = 0x08,//write, file does not exist is created, if the file already exists, then write new content after the original file content, the pointer position always at the last
Ios::trunc = 0x10,//Truncate file length to 0 before reading and writing (default)
Ios::nocreate = 0x20,//file does not exist error occurred, often and in or app joint use
Ios::noreplace = 0x40,//file exists with error, common and out joint use
ios::binary= 0x80//binary format file
File Protection options:
Filebuf::openprot; The default compatible sharing method
Filebuf::sh_none; Exclusive, not shared
Filebuf::sh_read; Read share
Filebuf::sh_write; Write share
How to open a file
Specify file name and open mode when calling constructors
Ifstream f ("D:\\12.txt", ios::nocreate); The default opens the file in Ios::in, and the operation fails when the file does not exist
Ofstream f ("D:\\12.txt"); Open a file by default in a ios::out manner
FStream f ("D:\\12.dat", ios::in|ios::out|ios::binary); To open a binary file in read-write mode
Using the Open member function
FStream F;
F.open ("D:\\12.txt", ios::out); Open function is used to manipulate multiple files using the same object
Check to see if open successfully
Success:
if (f) {...}//To Ifstream, Ofstream object is available, FStream object is unavailable.
if (F.good ()) {...}
Failed:
if (!f) {...}//! Operator already overloaded
if (F.fail ()) {...}
Read and write operations
Using the <<,>> operator
You can only read and write text files, and you may generate errors for binary files.
Use function member get, PUT, read, write, etc.
The function often used with Read is Gcount (), which is used to get the number of bytes actually read.
Reading and writing binary files considerations
Ios::binary must be specified in open mode, otherwise read-write error
Read and write with Read\write, not by using the INSERT, extract operator, or there will be an error.
Use the EOF () function to detect whether a file is read-finished, and to use Gcount () to get the actual number of bytes read
Close File
Use the member function close, such as:
F.close ();
Using destructors
The end of the object lifetime checks whether the file is closed and closes the file that is not closed.
Random Read and write files
You can read and write at the specified location of the file by moving the file read-write pointer.
SEEKG (absolute position);//absolute move,//input stream operation
SEEKG (relative position, reference position); Relative operations
TELLG ()//Returns the current pointer position
SEEKP (absolute position);//absolute move,//output stream operation
SEEKP (relative position, reference position); Relative operations
TELLP ()//Returns the current pointer position
Reference location:
ios::beg= 0//relative to file header
Ios::cur= 1//relative to current position
Ios::end= 2//relative to end of file
Examples of reading and writing text files
/To be able to correctly read the data written to the file, it is best to separate the data between

Copy Code code as follows:

#include <fstream.h>
void Main ()
{
FStream f ("D:\\try.txt", ios::out);
f<<1234<< ' <<3.14<< ' A ' << ' How to 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; Reading data
F.getline (s,20);
cout<<i<<endl; Show individual data
cout<<d<<endl;
cout<<c<<endl;
cout<<s<<endl;
F.close ();
}

Run Result:

1234
3.14
A
How to Are You
Press any key to continue

Display the contents of a text file

Read one character at a time using get ()--------------------------------scheme a

Copy Code code as follows:

#include <fstream.h>
void Main ()
{
Ifstream fin ("d:\\ profile. txt", ios::nocreate);
if (!fin) {
cout<< "File open error!\n";
Return
}
char c;
while ((C=fin.get ())!=eof) cout<<c; Notice the judgment of the end condition
Fin.close ();
}

Read more than one character at a time using get (char *,int n,char delim= ' \ n ')----scenario Two
Clever use of text files in the character ' "" does not have to read
#include <fstream.h>
void Main ()
{
Ifstream fin ("d:\\ profile. txt", ios::nocreate);
if (!fin) {
cout<< "File open error!\n";
Return
}
Char c[80];
while (Fin.get (c,80, '!=null ') cout<<c; Notice the judgment of the end condition
Fin.close ();
}
Reading a file using read (char *,int N)---------------------------scenario Three
#include <fstream.h>
void Main ()
{
Ifstream fin ("d:\\ profile. txt", ios::nocreate);
if (!fin) {
cout<< "File open error!\n";
Return
}
Char c[80];
while (!fin.eof ())//To determine whether the file is read end
{
Fin.read (c,80);
Cout.write (C,fin.gcount ());
}
Fin.close ();
}

Copy files
Examples of binary file operations

Copy Code 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";
}

Related Article

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.