参考博客:https://blog.csdn.net/qq_29406323/article/details/81261926#main-toc
- EOF——文件结束符,代表-1,表示文件的末尾
- 1.fstream提供了三个类,用来实现c++对文件的操作。(文件的创建、读、写)。
ifstream :从已有的文件读入
ofstream : 向文件写内容
fstream : 打开文件供读写
2.文件打开模式:
ios::in 只读
ios::out 只写
ios::app 从文件末尾开始写,防止丢失文件中原来就有的内容
ios::binary 二进制模式
ios::nocreate 打开一个文件时,如果文件不存在,不创建文件
ios::noreplace 打开一个文件时,如果文件不存在,创建该文件
ios::trunc 打开一个文件,然后清空内容
ios::ate 打开一个文件时,将位置移动到文件尾
3.文件指针位置的用法
ios::beg 文件头
ios::end 文件尾
ios::cur 当前位置
例子:
file.seekg(0,ios::beg); //让文件指针定位到文件开头
file.seekg(0,ios::end); //让文件指针定位到文件末尾
file.seekg(10,ios::cur); //让文件指针从当前位置向文件末方向移动10个字节
file.seekg(-10,ios::cur); //让文件指针从当前位置向文件开始方向移动10个字节
file.seekg(10,ios::beg); //让文件指针定位到离文件开头10个字节的位置
样例①:
#include <iostream>
#include <cstdio>
#include <fstream>
using namespace std;
ifstream fin("data.txt");// 文件中为:1 2
ofstream fout("out.txt"); //ios::trunc 打开一个文件,然后清空内容
int main()
{
int a, b;
fin>>a>>b;
fout << a <<" "<< b <<endl;
fin.close();
fout.close();
return 0;
}
样例②:
#include <iostream>
#include <cstdio>
#include <fstream>
using namespace std;
// ifstream fin("data.txt");// 文件中为:1 2
// ofstream fout("out.txt",ios::trunc); //ios::trunc 打开一个文件,然后清空内容
int main()
{
freopen("data.txt","r",stdin);
freopen("out.txt","w",stdout);
int a, b;
cin>>a>>b;
cout << a <<" "<< b <<endl;
return 0;
}