平时在读写文件时,我习惯了WIN32和C函数,今天试着用C++的风格来处理了一下。
注意operator<<和operator>>中被我注释掉的代码,因为os<<user.name<<user.age输出到文件后会连在一起(例如shadow20),之后读取时会全部作为字符串(可以在它们之间加个空格避免这个问题,不过我感觉这有点那啥)。所以我就使用了read/write(这里一个明显的缺点就是字符串可能用不到这么大的空间,可以考虑先写个字符串长度,接着再写字符串而不是整个数组)。
#include <fstream> #include <iostream> struct user { char name[32]; int age; }; std::ostream& operator<<(std::ostream & os, const user& user) { //os<<user.name<<user.age; os.write(user.name, sizeof(user.name)); os.write((const char*)&user.age, sizeof(user.age)); return os; } std::istream& operator>>(std::istream & is, user& user) { //is>>user.name>>user.age; is.read(user.name, sizeof(user.name)); is.read((char*)&user.age, sizeof(user.age)); return is; } int _tmain(int argc, _TCHAR* argv[]) { user users[2]; // 写文件 //strcpy_s(users[0].name, "shadow"); //strcpy_s(users[1].name, "avexer"); //users[0].age = 20; //users[1].age = 30; //std::ofstream fout("D:\\test.dat"/*, std::ios::binary*/); //fout<<users[0]<<users[1]; // 读文件 std::ifstream fin("D:\\test.dat"/*, std::ios::binary*/); fin>>users[0]>>users[1]; return 0; }