第五部分-文件操作
5、文件操作
1、文本文件
1.1 写文件
代码实例:
#include<iostream>
using namespace std;
#include<fstream>//头文件包含
//写文件
void test01() {
//包含头文件 fstream
//创建流对象
ofstream ofs;
//指定打开方式
ofs.open("text.txt", ios::out);
//写内容
ofs << "姓名:张三" << endl;
ofs << "性别:男" << endl;
ofs << "年龄:18" << endl;
//关闭文件
ofs.close();
}
int main() {
test01();
}
1.2 读文件
代码:
#include<iostream>
using namespace std;
#include<fstream>
#include<string>
void test01() {
//包含头部文件
//创建刘对象
ifstream ifs;
//打开文件 并且判断是否打开成功
ifs.open("text.txt", ios::in);
if (!ifs.is_open()) {
cout << "文件打开失败" << endl;
return;
}
//读数据
//第一种
/*char buf[1024] = { 0 };
while (ifs >> buf) {
cout << buf << endl;
}*/
////第二种
/*char buf[1024] = { 0 };
while (ifs.getline(buf, sizeof(buf))) {
cout << buf << endl;
}*/
//第三种
/*string buf;
while (getline(ifs, buf)) {
cout << buf << endl;
}*/
//第四种
char c;
while ((c = ifs.get()) != EOF) {
cout << c;
}
{
}
//关闭文件
ifs.close();
}
int main() {
test01();
}
2、二进制文件
1、写文件
代码:
#include<iostream>
using namespace std;
#include<fstream>
class Person {
public:
char m_Name[64];//姓名
int m_Age; //年龄
};
void test01() {
ofstream ofs;
ofs.open("person.txt", ios::out | ios::binary);
Person p = { "张三",18 };
ofs.write((const char*)&p, sizeof(Person));
ofs.close();
}
int main() {
test01();
}
总结:
文件输出流对象 可以通过write函数,以二进制方式写数据
2.2 读文件
代码:
#include<iostream>
using namespace std;
#include<fstream>
class Person {
public:
char m_Name[64];//姓名
int m_Age; //年龄
};
void test01() {
ifstream ifs;
ifs.open("person.txt", ios::in | ios::binary);
Person p ;
if (!ifs.is_open()) {
cout << "文件打开失败 " << endl;
return;
}
//读文件
ifs.read((char*)&p, sizeof(Person));
cout << "姓名" << p.m_Name << "年龄" << p.m_Age << endl;
ifs.close();
}
int main() {
test01();
}
文件输入流对象,可以通过read函数,以二进制方式读数据