C++ 文件操作
用于文件操作主要有两个类ifstream,ofstream,fstream,例子如下
1. 读操作
#include <ifstream> using name space std; int main() { cCar car; // initialize a car object ifstream in; in.open("test.txt", ios::in); //open file if (!in) { cout << "open file error" << endl; return 0; } while (in.read((char*) &car, sizeof(car))){ // read sizeof(car) bytes from file and write into memory &car cout << car.color << endl; }
in.close(); }
2. 写操作
#include <ofstream> using namespace std; int main() { cCar car; // initialize a car object ofstream 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 file out.close(); // opened file object must be closed at last.
}
3. 上面两个例子只是介绍了基本的读写操作,而且是逐字节顺序地操作文件。但是如果我想从文件中的中间一行读或写一个字节数字,可以做到不?
其实fstream, ofstream,ifstream里实现了很多方便实用的成员函数,完成刚才提到的问题只需要额外地操作一下读写指针就可轻松搞定。
何谓读写指针,就是指向当前字节流位置的指针,因此,只要我们控制好读写指针的位置,想在哪写入或读出都非常容易。
读写操作例子
#include <fstream> using namespace std; int main() { cCar car; // initialize a car object fstream f; f.open("test.txt", ios::in|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 beginning f.read((char*) &car, sizeof(car)); f.seekp(10); // location the 10th byte f.seekp(1, ios::cur); // jump to 1 bype from current point address f.seekp(1, ios::end); // jump to 1 byte from the end of file long loc = f.tellp(); // get the location which pointer point to
f.write("hellp", 6);
f.close(); }