需要包含头文件<fstream>
一、文本文件
配合使用时,可以用 | ,即ios::binary | ios::out
#include<bits/stdc++.h>
#include<fstream>
using namespace std;
int main() {
ofstream ofs;
ofs.open("testfiles.txt", ios::out); //往文件中写入内容
ofs << "123 123" << endl;
ofs << "456 456" << endl;
ofs.close();
//读取文件:
ifstream ifs;
ifs.open("testfiles.txt", ios::in);
if (!ifs.is_open()) {
cout << "Error!" << endl;
return 0;
}
//四种读取文件数据的方法
//1.
//char buf[10000] = { 0 };
//while (ifs >> buf) {
// cout << buf << endl;
//}
//2.
char buf[10000] = { 0 };
while (ifs.getline(buf, sizeof(buf))) { //两个参数,一个是指针,一个是读取的字节数
cout << buf << endl; //不能自动读取行末尾的回车符,要手动endl
}
//3.
string buf;
while (getline(ifs,buf)) { //不能自动读取行末尾的回车符,要手动endl
cout << buf << endl;
}
//4.
char c;
while ((c = ifs.get()) != EOF) {
cout << c;
}
ifs.close();
return 0;
}
二、二进制文件
打开方式要指定为ios::binary
#include<iostream>
#include<fstream>
using namespace std;
//二进制可以自定义写入的数据类型
class Person {
public:
int mAge;
char mName[10];
Person() {
}
Person(int age, const char name[]) { //这边要加个const防止出问题
this->mAge = age;
strcpy_s(mName,name);
}
};
int main() {
//文件写入操作
ofstream ofs("textbinary.txt", ios::out | ios::binary);
Person p(18, "cpx");
ofs.write((const char*)&p, sizeof(Person)); //注意这边写法
ofs.close();
//读文件操作
ifstream ifs("textbinary.txt", ios::in | ios::binary);
if (!ifs.is_open()) {
cout << "Error!" << endl;
return 0;
}
Person p2;
ifs.read((char*)&p2, sizeof(Person)); //注意这边写法
cout << p2.mName << " " << p2.mAge << endl;
ifs.close();
return 0;
}