There are two main classes Ifstream,ofstream,fstream for file operations, such as the following
1. Read operation
#include <ifstream>usingname space Std;intMain () {Ccar car; //Initialize a Car objectIfstreaminch; inch. Open ("Test.txt"Ios::inch);//Open File if(!inch) {cout<<"Open File Error"<<Endl; return 0; } while(inch. Read (Char*) &car,sizeof(car))) {//read sizeof (car) bytes from file and write into memory &carcout << Car.color <<Endl; }
In.close ();}
2. Write operations
#include <ofstream>using namespacestd;intMain () {Ccar car; //Initialize a Car objectOfstream out; out. Open ("Test.txt"Ios:: out);//Open File if(! out) {cout<<"Open File Error"<<Endl; return 0; } out. Write (Char*) &car,sizeof(car))//write sizeof (car) bytes from memory &car and write them into fileOut.close (); Opened file object must is closed at last.
}
3. The above two examples simply describe basic read and write operations, and manipulate the files in byte-wise order. But what if I want to read or write a byte number from the middle line in the file?
In fact, FStream, ofstream,ifstream in the implementation of a lot of convenient and practical member functions, complete the problem just mentioned only need to operate the read and write pointers to easily handle.
A read-write pointer is a pointer to the current byte stream position, so as long as we control the position of the read and write pointers, it is very easy to write or read them.
Examples of read and write operations
#include <fstream>using namespacestd;intMain () {Ccar car; //Initialize a Car objectFStream F; F.open ("Test.txt"Ios::inch|ios:: out);//Open file, it can be written and read at the same time. if(!f) {cout<<"Open File Error"<<Endl; return 0; } F.SEEKP (3*sizeof(int), Ios::beg);//Let Read/write point jump to the 4th int offset from beginningF.read ((Char*) &car,sizeof(car)); F.SEEKP (Ten);//Location the 10th byteF.SEEKP (1, ios::cur);//Jump to 1 bype from current point addressF.SEEKP (1, ios::end);//Jump to 1 bytes from the end of file Longloc = F.TELLP ();//get the location which pointer point to
F.write ("HELLP", 6);
F.close ();}
C + + file operations