二进制文件读写
二进制读文件
二进制写文件
在文件中写入并读取一个整数
#include <iostream>#include <fstream>using namespace std;void main() { ofstream fout("some.dat", ios::out | ios::binary); int x = 120; fout.write( (const char *) (&x), sizeof(int) ); fout.close(); ifstream fin("some.data", ios::in | ios::binary); int y; fin.read((char*) & y, sizeof(int)); fin.close(); cout << y << endl;}
从键盘输入几个学生信息,并以二进制文件保存
#include <iostream>#include <fstream>using namespace std;struct Student { char name[20]; int score;};void main() { Student s; ofstream OutFile("c:\\tmp\\students.dat", ios::out | ios::binary); while(cin >> s.name >> s.score) OutFile.write( (char*) & s, sizeof(s)); OutFile.close();}
将students.dat文件的内容读出并显示
#include <iostream>#include <fstream>using namespace std;struct Student { char name[20]; int score;};void main() { Student s; ifstream inFile("students.dat", ios::in | ios::binary); if(!inFile) { cout << "error" << endl; return 0; } while(inFile.read( (char*) & s, sizeof(s))) { int readedBytes = inFile.gcount(); // 看刚才读了多少字节 cout << s.name << " " << s.score << endl; } ifFile.close();}
将students.dat文件的Jane的名字改成Mike
#include <iostream>#include <fstream>using namespace std;struct Student { char name[20]; int score;};void main() { Student s; fstream iofile("c:\\tmp\\students.dat" ios::in | ios::out | ios::binary); if(!iofile) { cout << "error\n"; return } iofile.seekp( 2 * sizeof(s), ios::beg); // 定位写指针到第三个记录 iofile.write("Mike", strlen("Mike")+1); // +1是多写一个'\0' iofile.seekg(0, ios::beg); // 定位读指针到开头 while(iofile.read( (char*) & s, sizeof(s))) cout << s.name " " << s.score << endl; iofile.close();}/* 输出 Tom 60 Jack 80 Mike 40*/
二进制文件的优点
- 节省存储空间:字符文件每一个字符就是1个字节,而二进制文件不然
- 一个10位int类型数据,二进制文件需要4个字节,而字符文件需要10*1=10个字节
- 查找方便:二进制文件查找需要算得的字节偏移量好算,根据数据类型的sizeof()大小即可算出,而字符型数据不容易算
文件拷贝程序mycopy实例
/* 用法示例: mycopy src.dat dest.dat 将src.dat拷贝到dest.dat 如果dest.dat原来就有,则原来的文件会被覆盖*/#include <iostream>#include <fstream>using namespace std;int main(int argc, char * argv[]) { if(argc != 3) { cout << "File name missing!" << endl; return 0; } ifstream inFile(argv[1], ios::binary | ios::in); if(!inFile) { cout << "Source file open error." << endl; return 0; } ostream outFile(argv[2], ios::binary | ios::out); if(!outFile) { cout << "New file open error." << endl; inFile.close(); // 打开文件必须关闭 return 0; } char c; while(inFile.get(c)) // 每次读取一个字符,操作系统会把硬盘邻近区域全部取到内存缓冲区 outFile.put(c); // 每次写入一个字符 outFile.close(); inFile.close(); return 0;}
二进制文件和文本文件的区别

