【C++】文件操作

  • ~2.83K 字
  1. 1. 文件操作
    1. 1.1. 文本文件
      1. 1.1.1. 写文件
      2. 1.1.2. 读文件
    2. 1.2. 二进制文件
      1. 1.2.1. 写文件
      2. 1.2.2. 读文件

文件操作

C++中提供了文件流来对文件进行操作

需要引入头文件fstream

文件类型:

  • 文本文件:以ASCII码存储
  • 二进制文件:以二进制形式存储

操作文件三大类:

  • ofstream:写
  • ifstream:读
  • fstream:读/写

文本文件

写文件

1
2
3
4
5
6
7
8
#include <fstream>
using namespace std;
int main(){
ofstream ofs; // 创建流对象
ofs.open("路径", <打开方式>) // 指定打开方式
ofs << "写入的数据"; // 写内容
ofs.close(); // 关闭文件
}

其中打开方式有:

打开方式 解释
ios::in 读文件而打开文件
ios::out 写文件而打开文件
ios::ate 文件打开时指针位于文件末尾,可以移动指针进行读写
ios::app 所有读写操作都会添加到文件末尾
ios::trunc 若文件存在则先删除再创建
ios::binary 二进制方式操作

可以使用|操作符来配合使用多个文件操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<iostream>
#include<fstream>
using namespace std;
int main(){
// 创建流对象
ofstream ofs;
// 指定打开方式
ofs.open("test.txt", ios::out);
// 写内容
ofs << "name: Li Hua"<<endl;
ofs << "age: male"<<endl;
// 关闭文件
ofs.close();
}

读文件

1
2
3
4
5
6
7
8
#include <fstream>
using namespace std;
int main(){
ifstream ofs; // 创建流对象
ofs.open("路径", <打开方式>) // 打开文件并判断是否成功
ofs << "写入的数据"; // 读取数据
ofs.close(); // 关闭文件
}

其中读取数据有多种方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include<iostream>
#include<fstream>
#include <string>
using namespace std;
int main(){
// 创建流对象
ifstream ifs;
// 打开文件
ifs.open("test.txt", ios::in);
// 判断打开是否成功
if(!ifs.is_open()){
cout <<"Open failed";
return 0;
}
// 读取数据
// 方式1: 使用字符数组,但遇到空格也会停下
char buf[1024]={};
while(ifs>>buf){
cout << buf << endl;
}

// 方式2: 使用getline,只有遇到回车才会停下
char buf2[1024]={};
while(ifs.getline(buf2, sizeof buf2)){
cout << buf << endl;
}

// 方式3:使用string
string bufs;
while(getline(ifs, bufs)){
cout << buf << endl;
}

// 方式4:使用char,一个个读取
char c;
while((c=ifs.get())!=EOF){
cout << c;
}
ifs.close();

}

二进制文件

二进制打开方式指定为ios::binary

写文件

注意:写入二进制文件时,不建议使用string,会引发指针异常

使用write方式来写入文件,而不是用流式输入,对一个对象我们使用const char*这样一个常量指针类型取得对象实例地址后进行写入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<iostream>
#include<fstream>
using namespace std;
class person{
public:
char name[64];
int age;
};
int main(){
ofstream ofs;
ofs.open("person.txt", ios::out|ios::binary);
person p = {"Jack", 18};
ofs.write((const char*)&p, sizeof(person));
ofs.close();
}

读文件

使用read方式来读文件

参数原型:istream& read(char *buffer, int len);

即字符指针buffer指向内存中一段存储空间,len为读写的字节数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<iostream>
#include<fstream>
using namespace std;
class person{
public:
char name[64];
int age;
};

int main(){
ifstream ifs;
ifs.open("person.txt", ios::in|ios::binary);
if(!ifs.is_open()){
cout <<"Open failed";
return 0;
}
person p;
ifs.read((char *)&p, sizeof(person));
cout << "name: "<<p.name<<endl;
cout << "age: "<<p.age<<endl;

ifs.close();
}
赞助喵
非常感谢您的喜欢!
赞助喵