C++文件操作
文件分类 - 文本文件:ASCII码存储 - 二进制文件:二进制存储
操作文件三大类: -ofstream:写 -ifstream:读 -fstream:读写 ## 写文件
- 需包含头文件#include<fstream> -
创建流对象ofstream ofs; -
打开文件ofs.open("文件路径","打开方式"); -
写数据ofs<<"写入的数据"; -
关闭文件ofs.close();
文件打开方式: |打开方式|作用| |:---|:---| |ios::in|读文件|
|ios::out|写文件| |ios::ate|初始位置为文件尾| |ios::app|追加方式写|
|ios::trunc|先删除,再创建| |ios::binary|二进制方式写|
可以使用|用多种方式打开:ios::in|ios::out ## 读文件 -
需包含头文件#include<fstream> -
创建流对象ifstream ifs; -
打开文件ifs.open("文件路径","打开方式"); - 读数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24//方法一
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 (ifs.getline(buf,sizeof(buf)))
{
cout << buf << endl;
}
//方法四
char c;
while ((c = ifs.get()) != EOF) //EOF: end of file
{
cout << c;
}ifs.close();
二进制文件读写
写文件: ofs.write((const char *)&p, sizeof(p));
读文件: ifs.read((char *)&p, sizeof(p)));