实测: 参照《C++文件操作详解》fstream 不能用,以下采用 iftream和oftream类实现。
读写文件
二进制文件的读写
读写数据块
要读写二进制数据块,使用成员函数read()和write()成员函数,它们原型如下:
read(unsigned char *buf,int num); write(const unsigned char *buf,int num);
read() 从文件中读取 num 个字符到 buf 指向的缓存中,如果在还未读入 num 个字符时就到了文件尾,可以用成员函数 int gcount();来取得实际读取的字符数;而 write() 从buf 指向的缓存写 num 个字符到文件中,值得注意的是缓存的类型是 unsigned char *,有时可能需要类型转换。
实例
必须包含
#include<fstream> using namespace std;
#include <iostream> #include<fstream> using namespace std; #define LEN 10 int main() { ofstream file_out; ifstream file_in; /// <文件写入> file_out.open("Demo1.dat", ios::binary | ios::app | ios::in);//二进制、追加方式、文件输入方式 if (!file_out.is_open()) { cout << "文件打开异常!"; return 0; } short arr1[LEN]; for (int i = 0; i < LEN; i++) { arr1[i] = i * 2; cout << arr1[i] << endl; } for ( int i = 0; i < LEN; i++) { file_out.write(reinterpret_cast<char*>(arr1), sizeof(short) * LEN); } file_out.close(); /// </文件写入> /// <文件读取> short read[LEN]; file_in.open("Demo1.DAT", ios::binary | ios::out);//二进制、文件读取方式 file_in.seekg(0, ios::beg); for (int i = 0; i < LEN; i++) { file_in.read(reinterpret_cast<char*>(read), sizeof(short) * LEN); file_in.seekg(sizeof(short) * LEN, ios::cur); } for (int i = 0; i < LEN; i++) { cout << read[i] << endl; } file_out.close(); /// </文件读取> }
实验结果