C++ read and write file flow example procedures

  • 2020-04-02 01:58:41
  • OfStack

Master the method of reading and writing text files
Learn how to read and write binary files

C++ file stream:


fstream  //File stream
ifstream  //Input file stream
ofstream  //Output file stream

//Create a text file and write the information
//Output information to a file just as you output information to the screen
#include<iomanip.h>
#include<fstream.h>
void main()
{
  ofstream f1("d:\me.txt");           //Open the file for writing and create it if it doesn't exist
  if(!f1)return;                 //Failure to open the file ends the run
  f1<<setw(20)<<" Name: "<<" Cheap east "<<endl;     //Writes the contents of the file using the insert operator
  f1<<setw(20)<<" Home address: "<<" Henan zhengzhou "<<endl;
  f1.close();                   //Close the file
}

After running open file d: \ me.txt, its content such as: name: lian dongfang home address: zhengzhou, henan

File operation:
Open the file
The file name
Note that the slash in the pathname should be double, such as: "D:\\MyFiles\\ readme.txt"
File opening mode options:
Ios ::in= 0x01,// for reading, file is created if it does not exist (ifstream opens by default)
Ios ::out = 0x02,// for writing, if the file does not exist, create it, if the file already exists, empty the original content (ofstream opens by default)
Ios ::ate = 0x04,// when the file opens, the pointer is at the end of the file. Can change the position of the pointer, often used in conjunction with in, out
Ios ::app = 0x08,// for writing, the file is created if it does not exist, if the file already exists, the new content is written after the original file content, the pointer position is always at the end
Trunc = 0x10,// truncate the file length to 0 before reading or writing (default)
Error occurs when ios::nocreate= 0x20,// file does not exist, often used in conjunction with in or app
Ios ::noreplace = 0x40,// error occurred while file exists, often used in conjunction with out
Ios ::binary= 0x80 // binary format file
File protection mode option:
Filebuf: : openprot; // the default mode of compatible sharing
Filebuf: : sh_none; // exclusive, not Shared
Filebuf: : sh_read; / / read to be Shared
Filebuf: : sh_write; / / write to share
Method to open a file
Specify the file name and open mode when the constructor is called
Ifstream f (" d: \ \ 12. TXT ", the ios: : nocreate); // by default, the file is opened in the mode of ios::in. The operation fails when the file does not exist
Ofstream f (" d: \ \ 12. TXT "); // opens the file with ios::out by default
Fstreamf (" d: \ \ 12. Dat ", the ios: : | in ios: : out | ios: : binary); // opens the binary file as a read and write
Use the Open member function
Fstream f;
F.o pen (" d: \ \ 12. TXT ", the ios: : out); // the open function is used to manipulate multiple files using the same object
Check that it has been successfully opened
Success:
If (f) {... }// is available for ifstream and ofstream objects, but not for fstream objects.
If (f.g ood ()) {... }
Failure:
If (! F) {... } / /! The operator has been overloaded
If (f.f ail ()) {... }
Read and write operations
use < < . > > The operator
Only text files can be read and written, and using binary files can cause errors.
Use function members get, put, read, write, and so on
A function that is often used in conjunction with read is gcount() to get the number of bytes actually read.
Notes for reading and writing binary files
Open mode must specify ios::binary, otherwise read and write error
Read write instead of insert and extract operators will cause errors.
Use the eof() function to detect if the file is read, and use gcount() to get the number of bytes actually read
Close the file
Use the member function close, such as:
F. lose ();
Use the destructor
At the end of the object's life, the file is checked to see if it is closed, and the file that is not closed is closed.
Random read and write file
By moving the file read/write pointer, you can read/write at the specified location in the file.
Seekg (absolute location); // absolute move, // input stream operation
Seekg (relative position, reference position); // relative operation
Tellg (); // returns the current pointer position
Seekp (absolute position); // absolute move, // output stream operation
Seekp (relative position, reference position); // relative operation
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 the end of the file
Example of reading and writing a text file
/ in order to correctly read the data written to the file, it is better 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 the data
f.getline(s,20);
cout<<i<<endl; //Display each data
cout<<d<<endl;
cout<<c<<endl;
cout<<s<<endl;
f.close();
}

Operation results:

1234
3.14
a.
How are you
Press any key to continue

Displays the contents of a text file

Use get() to read one character at a time


#include<fstream.h>
void main()
{
ifstream fin("d:\ Introduction to the .txt",ios::nocreate);
if(!fin){
cout<<"File open error!n";
return;
}
char c;
while((c=fin.get())!=EOF)cout<<c;  //Notice the end condition
fin.close();
}
//Use get(char *,int n,char delim='n') to read more than one character at a time -- option 2
//Clever use of the text file will not have the character '0' to read
#include<fstream.h>
void main()
{
ifstream fin("d:\ Introduction to the .txt",ios::nocreate);
if(!fin){
cout<<"File open error!n";
return;
}
char c[80];
while(fin.get(c,80,'0')!=NULL)cout<<c; //Notice the end condition
fin.close();
}
//Use the read (char *, int n) to read file -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- three
#include<fstream.h>
void main()
{
ifstream fin("d:\ Introduction to the .txt",ios::nocreate);
if(!fin){
cout<<"File open error!n";
return;
}
char c[80];
while(!fin.eof())  //Determines whether the file is read
{
fin.read(c,80);
cout.write(c,fin.gcount()); 
}
fin.close();
}

Copy files
Example binary file manipulation


#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 articles: