文件操作
1、文件的定义和打开
ifstream类: 读文件
ofstream类: 写文件
专类专事(只能进行读或者写)
所以我们会使用fstream去操作文件,它时ifstream和ofstream类的父类。
定义文件 fstream file;
1.打开文件
file.open(char* fileURL,int mode);
mode:
ios::in 读
ios::out 写(清空重写)
ios::app 追加模式 不具有创建功能
ios::trunc: 覆盖已经存在的文件
ios::binary 二进制写法
组合方式 |
ios::in | ios::out
判断文件是否打开: !file || !file.is_open任选其一,均可。
2.读写文件
读写有2种的方式:
2.1 流的方式做读写
2.2 成员函数的方式做读写 字节流
write(源地址,大小) 函数
read(源地址,大小) 函数
在读写时是以空格为分隔符,
fd << str2 << " " << 4 ;
fd.seekg(0, ios::beg); //指针移动回去 字节方式移动
int num=0;
char str[20] = " ";
fd >> str>>num; //要用类型对应的接收
注意在读写时,要记住你动了文件指针,需要回到原来时,记得移动。
3.关闭文件
file.close();
4.文件移动
C语言:fseek
seekg( size_t size , int position )
ios::beg 开头
ios::end 结尾
ios::cur 当前
5、文件指针位置获取
tellg(); //移动字节数
代码
以流的方式
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
fstream fd;
fd.open("2.txt", ios::out |ios::in);
if (!fd || !fd.