头文件
#include <iostream>
#include <fstream>
文件读写模式:
基本读写(精准读写):
//基本读写,精准读写
fstream fd;
fd.open("test.txt",ios::out | ios::trunc);
fd.put('s');
fd.put('q');
fd.close();
fd.open("test.txt", ios::in );
char ch = fd.get();
cout << ch << endl;
fd.close();
二进制读写:
二进制读写优点是效率高
缺点是保存的文件直接看不懂
使用小端模式读写
fstream file;
file.open("test2.txt", ios::out );
int num = 99;
file.write((const char *)&num,sizeof(int));
file.close();
file.open("test2.txt", ios::in);
int val = 0;
file.read((char*)&val, sizeof(int));
file.close();
cout <<"val = " << val << endl;
<<与>>读写(方便快捷)
fstream file2;
file2.open("test3.txt", ios::out);
file2 << "我最厉害,士大夫hiUSD回复" << endl;
file2 << "123" << endl;
file2.close();
string str21;
int dsf = 0 ;
file2.open("test3.txt", ios::in);
file2 >> str21;
file2 >> dsf;
cout << "str21 = " << str21 << endl;
cout << "dsf = " << dsf << endl;
file2.close();