二进制文件读写:下面的程序从键盘输入几个学生的姓名和成绩,并以二进制文件形式存起来
#include <iostream> #include <fstream> #include <cstring> using namespace std; class CStudent { public: char szName[20]; int nScore; }; int main() { CStudent s; ofstream OutFile("c:\\tmp\\students.dat", ios::out | ios::binary); while (cin >> s.szName >> s.nScore) { if (strcmp(s.szName, "exit") == 0) break; OutFile.write((char*)&s, sizeof(s)); } OutFile.close(); return 0; }
二进制文件读写:下面的程序将students.dat文件的内容读出并显示
#include <iostream> #include <fstream> using namespace std; class CStudent { public: char szName[20]; int nScore; }; int main() { CStudent s; ifstream inFile("C:\\Users\kang3\Desktop\students.dat", ios::in | ios::binary); if (!inFile) { cout << "error" << endl; return 0; } while (inFile.read((char*)&s, sizeof(s))) { int nReadedBytes = inFile.gcount();//看刚才读了多少字节 cout << s.szName << " " << s.nScore << endl; } inFile.close(); return 0; }
二进制文件读写:下面的程序将 students.dat 文件的Jane的名字改成Mike
#include <iostream> #include <fstream>
using namespace std; class CStudent { public: char szName[20]; int nScore; }; int main() { CStudent s; fstream iofile("D:\tmp\students.dat", ios::in|ios::out | ios::binary); if (!iofile) { cout << "error"; return 0; } iofile.seekp(2 * sizeof(s), ios::beg);//定位写指针到第三个记录 iofile.write("Mike", strlen("Mike") + 1); iofile.seekg(0, ios::beg); //定位读指针到开头 while (iofile.read((char*)&s, sizeof(s))) cout << s.szName << " " << s.nScore << endl; iofile.close(); return 0; }
例子: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; } ofstream 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; }
No comments:
Post a Comment