1.写文件
//文件操作
#include<fstream>
int main() {
//写文件
//路径 -- 此路径没有就生成给文件
string filePath = R"(E:\项目\test.txt)";
//打开文件 ios::app在后面追加内容 啥也不跟是覆盖写入
ofstream fout(filePath, ios::app);
//检查是否打开成功
if (fout.is_open() == false) {
cout << "打开文件失败...\n";
return 0;
}
//写入内容
fout << "张三爱李四\n";
fout << "李四爱王五\n";
fout << "王五爱马六\n";
//关闭文件
fout.close();
cout << "文件写入成功\n";
return 0;
}
2.读文件
//文件操作
#include<fstream>
#include<string>//读文件要用
int main() {
//读文件
//路径 -- 此路径没有就生成给文件
string filePath = R"(E:\项目\test.txt)";
//打开文件
ifstream fin(filePath);
//检查是否打开成功
if (fin.is_open() == false) {
cout << "打开文件失败...\n";
return 0;
}
//读取内容
第一种方法
//string buffer;//读取出来的一行内容放到buffer
//while (getline(fin, buffer)) {
// cout << buffer << endl;
//}
// //第2种方法
//char buffer[101];//设置为缓冲区
// //这不是全局的getline
//while (fin.getline( buffer,100)) {
// cout << buffer << endl;
//}
//第2种方法
string buffer;//读取出来的一行内容放到buffer
while (fin>>buffer) {//一行一行的读到buffer里面 读完返回空
cout << buffer << endl;
}
//关闭文件
fin.close();
cout << "文件读取成功\n";
return 0;
}
3.二进制写入
//文件操作
#include<fstream>
int main() {
//写文件
//路径 -- 此路径没有就生成给文件
string filePath = R"(E:\项目\test.txt)";
//打开文件 ios::app在后面追加内容 啥也不跟是覆盖写入
//以二进制方式 写入
ofstream fout(filePath, ios::app|ios::binary);
//检查是否打开成功
if (fout.is_open() == false) {
cout << "打开文件失败...\n";
return 0;
}
//写入内容写入一个超女结构体
struct st_girl {
char name[31];
int bh;
char message[31];//备注
double weight;
};
struct st_girl sgirl = { "陈小明",1,"中国四大帅哥之一",10000 };
// 传入结构体地址 结构体大小
fout.write((const char*)& sgirl, sizeof(sgirl));
sgirl = { "李小彬",2,"中国四大帅哥之一",0.1 };
fout.write((const char*)&sgirl, sizeof(sgirl));
//关闭文件
fout.close();
cout << "文件写入成功\n";
return 0;
}
4.读出二进制文件
//文件操作
#include<fstream>
#include<string>//读文件要用
int main() {
//读文件
//路径 -- 此路径没有就生成给文件
string filePath = R"(E:\项目\test.txt)";
//打开文件 以二进制打开
ifstream fin(filePath,ios::binary);
//检查是否打开成功
if (fin.is_open() == false) {
cout << "打开文件失败...\n";
return 0;
}
//读取内容 怎么写进去就怎么读出来 之前是结构体这也要定义一个一模一样的结构体
//一个超女结构体
struct st_girl {
char name[31];
int bh;
char message[31];//备注
double weight;
}girl;
//循环读取
while (fin.read((char*)&girl, sizeof(girl))) {
cout << "name= " << girl.name << " bh= " << girl.bh << " message= " << girl.message <<
" weight= " << girl.weight << endl;
}
//关闭文件
fin.close();
cout << "文件读取成功\n";
return 0;
}