文件操作
1.头文件fstream
2.文件类型有两种:文本文件 ,二进制文件
3.操作文件的三大类
ofstream:写操作
ifstream:读操作
fstream:读写操作
写文件
1.包含头文件
#include<fstream>
2.创建流对象
ofstream ofs;
3 打开文件
ofs.open("文件路径",打开方式);
4.写数据
ofs<< "写入数据";
5 关闭文件
ofs.close();
文件的打开方式
文件打开方式可以配合使用,利用 "|"操作符;
如:利用二进制方式写文件ios::binary | ios::out
代码示例
#include <iostream>
#include <algorithm>
#include <string>
#include <fstream>
using namespace std;
int main()
{
//创建对象
ofstream ofs;
ofs.open("lcl.txt",ios::out);
ofs<<"姓名:lcl" <<endl;
ofs<<"性别:man" <<endl;
ofs<<"age: 18" <<endl;
ofs.close();
return 0;
}
结果输出
读文件
#include <iostream>
#include <algorithm>
#include <string>
#include <fstream>
using namespace std;
#include <unistd.h>
int main()
{
//创建对象
ifstream ifs;
ifs.open("lcl.txt",ios::in); //以读的方式打开
if(!ifs.is_open())
{
cout << "open failed"<<endl;
return -1;
}
//方法1
char buf[1024] = {0}; //定义数组后,内存中就已经开辟的相应大小的空间,如果是指针,则需要去分配内存
while (ifs >> buf) //ifs 中存放从打开文件中读取的内容,每次读去1024个字节到buf中
{
cout <<"1 " <<buf <<endl;
sleep(1);
}
//方法2
char buf1[1024] = {0};
while(ifs.getline(buf1,sizeof(buf1))) //每次获取一行到buf中
{
cout <<"2 " <<buf1 <<endl;
sleep(1);
}
//方法3
string buf2;
while(getline(ifs,buf2))
{
cout <<"3 " <<buf2 <<endl;
}
//方法4
char c;
while((c = ifs.get()) != EOF) //end of file
{
cout << c;
}
ifs.close();
return 0;
}