c++文件读写
先上一张镇楼图
再来一个demo
#include <iostream> #include <fstream> #include <string> #define BUFFER_SIZE 128 using namespace std; struct Person { string name = "xiaoming"; int age = 18; bool isHe = false; }; int main() { ofstream writer("test.txt"); if (!writer.is_open()) { cout << "ofstream open file failed" << endl; return 1; } writer << "first line\n"; writer << 100 << "\n"; writer << "third line\n"; writer << "fourth line"; writer.close(); ifstream reader("test.txt"); char buffer[BUFFER_SIZE]; while (reader.getline(buffer, BUFFER_SIZE)) { cout << "current line: " << buffer << endl; } reader.close(); cout << "read done" << endl; writer.open("test.bin", ios::binary); Person daming; daming.name = "daming"; daming.age = 28; daming.isHe = true; writer.write((char*)&daming, sizeof(struct Person)); writer.close(); reader.open("test.bin", ios::binary); Person target; reader.read((char*)&target, sizeof(struct Person)); cout << target.name << endl; cout << target.age << endl; cout << target.isHe << endl; cout << "read done" << endl; }
PS: