c++结构体写入文档
//#include<iostream>
//#include<fstream>
//using namespace std;
// struct student
// {
// char name[20];
// char sex[20];
// int age;
// };
// int main()
// {
// const int num = 2;
// student stu[num];
// string path = "1.txt";
// fstream fout(path, ios::out | ios::app);
//
// if (fout.fail())
// {
// cout << "文件打开失败" << endl;
// exit(0);
// }
//
// for (int i = 0; i < num; i++)
// {
// cout << "姓名:";
// cin >> stu[i].name;
// cout << "性别:";
// cin >> stu[i].sex;
// cout << "年龄:";
// cin >> stu[i].age;
//
// fout << stu[i].name << " " << stu[i].sex << " " << stu[i].age << endl;
// }
//
// fout.close();
// }
第一种不会出现乱码
//#include <fstream>
//#include<iostream>
//using namespace std;
//struct student {
// char name[20];
// int age;
// float score;
//};
//int main() {
// ofstream ofs("studenms.txt", ios_base::_Noreplace);
// if (!ofs) {
// cerr<< "open file students.dat failed" << endl;
// return -1;
// }
//
// struct student s1 = { "Tom", 18, 85.5 };
// struct student s2 = { "Jerry", 19, 78.9 };
//
// ofs.write((char*)&s1, sizeof(s1));
// ofs.write((char*)&s2, sizeof(s2));
//
// ofs.close();
// return 0;
//}
//#include<iostream>
//#include<fstream>
//using namespace std;
//struct student
//{
// char name[20];
// int num;
// int age;
// char sex;
//};
//int main()
//{
// student stud[3] = { "Li",1001,18,'f',"Fun",1002,19,'m',"Zhao",1003,20,'m' };
// ofstream outfile;
// outfile.open("stuhud.txt", ios::binary);
// if (!outfile)
// {
// cout << "error";
// abort();
// }
// for(int i=0;i<3;i++)
// {
// outfile.write((char*)&stud[i], sizeof(stud[i]));
// }
// outfile.close();
// return 0;
//}
打开后不能直接查看
将结构体写入文件,文件中的数据是以二进制形式存储的,这些二进制数据不能直接被文本编辑器解释为字符,所以在用文本编辑器打开文件时就会出现乱码。
如果需要查看文件中的数据,可以使用一些专门的工具,例如hexdump或od等命令行工具,或者使用Windows系统中的十六进制编辑器。这些工具可以以二进制的形式呈现文件中的数据,使得我们可以更加直观地查看和分析文件中的内容。
本文来自博客园,作者:赵千万,转载请注明原文链接:https://www.cnblogs.com/zhaoqianwan/p/17378465.html
千万千万赵千万