文本文件
1.文本文件 ASCII码
2,二进制文件 二进制存
操作文件三大类
1.ofstream写操作
2.ifstream读文件
3.fstream 读写文件
写文件
1.#include <fstream
2.创建流对象
ofstream ofs;
3.打开文件
ofs.open("文件路径",打开方式);
4.写数据
ofs<<"写入的数据";
5.关闭文件
ofs.close();
文件打开方式
ios::in 以只读方式打开文件(只能读,不能写)
ios::out 以只写方式打开文件→ 会清空原有内容
ios::app 以追加方式写文件→ 不会清空,写在文件末尾
ios::ate 打开文件后,定位到文件末尾(但可以修改前面内容)
ios::trunc 打开时清空文件内容(默认和 out 一起生效)
ios::binary 以二进制模式打开(不做文本转换)
javascript
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<fstream>
using namespace std;
void test01(){
//1.包含头文件
//2.创建流对象
ofstream ofs;
//3.指定打开方式
ofs.open("test.txt", ios::out);
//4.写内容
ofs << "姓名:张三" << endl;
ofs << "年龄:18" << endl;
ofs << "性别:男" << endl;
//5.关闭
ofs.close();
}
int main() {
test01();
}
读文件
1.包含头文件
#include<fstream
2.创建流对象
ifstream ifs;
3.打开文件并判断文件是否打开成功
ifs.open("文件路径",打开方式);
4.读数据
四种方式读取
5.关闭文件
ifs.close()
javascript
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void test01(){
//1.包含头文件
//2.创建流对象
ifstream ifs;
//3.打开文件 并且判断是否打开成功
ifs.open("test.txt", ios::in);
if (!ifs.is_open()) {
cout << "文件打开失败" << endl;
return;
}
//4.读数据
//第一种
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;
//getline结束会返回false或者EOF
}
//第四种
char c;
while ((c = ifs.get()) != EOF) {
cout << c;
}
//5.关闭文件
ifs.close();
}
int main() {
test01();
}
用二进制写文件
javascript
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class person {
public:
char m_name[100];
int m_age;
};
void test01(){
ofstream ofs;
ofs.open("text.txt", ios::out | ios::binary);
person p = { "张三",18 };
ofs.write((const char*)&p, sizeof(p));
ofs.close();
}
int main() {
test01();
}
用二进制读文件
javascript
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class person {
public:
char m_name[100];
int m_age;
};
void test01(){
ifstream ifs;
ifs.open("test.txt", ios::in | ios::binary);
if (!ifs.is_open()) {
cout << "文件打开失败" << endl;
return;
}
person p;
ifs.read((char*)&p, sizeof(person));
cout << "姓名" << p.m_name << endl;
cout << "年龄" << p.m_age << endl;
ifs.close();
}
int main() {
test01();
}