1.涉及到的类和方法
fstream--》子类 ifstream 跟文件的读取有关
子类ofstream 跟文件的写入有关
#include<fstream>2.读取文件
(1)创建 ifstream的对象
ifstream();
ifstream (const char* filename, ios_base::openmode mode = ios_base::in);
参数: filename --》你要读取的文件路径名
mode --》权限
ios_base::in 可读 O_RDONLY
ios_base::out 可写 O_WRONLY
ios_base::trunc 覆盖 O_TRUNC
(2)打开文件
void open (const char* filename, ios_base::openmode mode = ios_base::in);(3)读取文件
istream& read (char* s, streamsize n);
istream& getline (char* s, streamsize n ); //一次最多只能读取一行数据,类似于fgets()
istream& getline (char* s, streamsize n, char delim ); //参数delim作为读取一行的分界符(默认getline以回车作为一行的分界符)
istream& get (char& c); //读取一个字符
istream& get (char* s, streamsize n); //读取n个字符(4)关闭文件
void close();3.写入文件
(1)创建ofstream对象
ofstream();
ofstream (const char* filename, ios_base::openmode mode = ios_base::out);(2)打开文件
void open (const char* filename, ios_base::openmode mode = ios_base::in);(3)写入文件
ostream& write (const char* s, streamsize n);
(4)关闭文件
void close();4.设置读写偏移
linux--》lseek()/fseek()
设置读的偏移: istream& seekg (streamoff off, ios_base::seekdir way);
设置写的偏移: ostream& seekp (streamoff off, ios_base::seekdir way);
参数: off --》你打算偏移多少字节
way --》从哪个位置开始偏移
ios_base::beg //起始位置
ios_base::cur //当前位置
ios_base::end //末尾位置
写入文件使用ofstream的带参构造函数和无参构造函数
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
//创建ofstream的对象
ofstream stream("./new.txt");
//打开--》错误的ofstream stream("./new.txt")具备打开功能
//stream.open("./new.txt");
//写入内容
stream.write("冬至吃汤圆",15);
//关闭文件
stream.close();
return 0;
}
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
//创建ofstream的对象
ofstream stream;
//打开
stream.open("./other.txt");
//写入内容
stream.write("新年快乐2022",16);
//关闭文件
stream.close();
return 0;
}
大文件分段读取拷贝
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
//定义缓冲区存放读取的内容
char buf[1024*1024]; //1M
//打开源文件
ifstream in;
in.open("./1.mp4");
//新建目标文件
ofstream out("./2.mp4");
//循环读取,循环写入
while(1)
{
//读取源文件
in.read(buf,1024*1024); //5000
//把读取的内容写入到目标文件中
out.write(buf,in.gcount());
//读到文件末尾就退出循环
if(in.eof())
break;
}
//关闭文件
in.close();
out.close();
return 0;
}