文件
C++可以将进行文件操作。C++使用文件的时候需要包含#include<fstream>
这个库。
文件类型分为两种,一种是二进制文件,一种是文本文件。他们分别对应两大种存储方式。一个我们可以通过类似于记事本方式打开,一个一般情况之下我们看不太懂。
文本文件
- 包含头文件
#include<fstream>
- 创建流对象
ofstream ofs;
- 打开文件
ofs.open("文件路径",打开方式);
- 写数据
ofs << "写入的数据";
- 关闭文件
ofs.close();
文件打开方式:
打开方式 | 解释 |
---|---|
ios::in | 为读文件而打开文件 |
ios::out | 为写文件而打开文件 |
ios::ate | 初始位置:文件尾 |
ios::app | 追加方式写文件 |
ios::trunc | 如果文件存在先删除,再创建 |
ios::binary | 二进制方式 |
注意: 文件打开方式可以配合使用,利用|操作符
例如:用二进制方式写文件 ios::binary | ios:: out
for example:
//文件-1(文本文件写入)
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream ofs1;
ofs1.open("1.txt",ios::out);
ofs1<<"我是你的爸爸"<<endl;
ofs1<<"66666"<<endl;
ofs1.close();
}
读文件其实类似,只需要把输出流fstream改为输入流ifstream就可以了,头文件不变。看代码
//文件-2(文本文件读取)
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream ifs1;
ifs1.open("1.txt",ios::in);
if (!ifs1.is_open())
{
cout << "文件打开失败" << endl;
return 0;
}
//第一种方式
//char buf[1024] = { 0 };
//while (ifs >> buf)
//{
// cout << buf << endl;
//}
//第二种
//char buf[1024] = { 0 };
//while (ifs1.getline(buf,sizeof(buf)))
//{
// cout << buf << endl;
//}
//第三种
//string buf;
//while (getline(ifs1, buf))
//{
// cout << buf << endl;
//}
char c;
while ((c = ifs1.get()) != EOF)//EOF:end of file
{
cout << c;
}
ifs1.close();
}
二进制文件
二进制文件的读取和写入,可以用以下两个函数原型:
写入:ostream& write(const char * buffer,int len);
参数解释:字符指针buffer指向内存中一段存储空间。len是读写的字节数
读取:istream& read(char *buffer,int len);
参数解释:字符指针buffer指向内存中一段存储空间。len是读写的字节数
同时加上|操作符,ios::binary以二进制打开就可以了
for example