大家好,又见面了,我是你们的朋友全栈君。
#include<iostream> #include<fstream> using namespace std; class Stu { public: char name[10]; int id; Stu() { strcpy_s(name, “Z”); id = 0; } Stu(char *n, int i) { strcpy_s(name, n); id = i; } }; int main() { ofstream out1; out1.open(“d.dat”, ios::binary); Stu s1[3]; s1[0] = { “A”, 10 }; s1[1] = { “B”, 20 }; s1[2] = { “C”, 30 };
for (int i = 0; i < 3; i++) { out1.write((char*)&s1[i], sizeof(s1[i]));//保存到磁盘中 } out1.close(); out1.open(“d.dat”, ios::binary); out1.seekp(2 * sizeof(s1[0]), ios::cur);//将磁盘文件指针设置到s1[2]的位置 Stu ss(“lin”, 20); out1.write((char*)&ss, sizeof(ss));//修改s1[2]的值
out1.close();
ifstream in1; Stu p; in1.open(“d.dat”, ios::binary); in1.seekg(2*sizeof(s1[0]), ios::cur);//将文件指针设置到s1[2]的位置 in1.read((char *)&p, sizeof(s1[1]));//读取s1[2]的值,检查修改后是否成功 cout << “name:” << p.name <<‘\t'<< “id:” << p.id << endl; in1.close(); return 0; }
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/140919.html原文链接:https://javaforall.cn