一,写文件一般流程
文件分为两种:文本文件与二进制文件,
文本文件:以ASCII码方式存储在计算机中
二进制文件:以二进制方式存储在计算机中,一般不能访问
对文件的操作分为三种:
ofstream : 写操作
ifstream : 读操作
fstream : 读写操作
#include <iostream>
#include <string>
#include <fstream> //1,包含头文件
using namespace std;
int main() {
ofstream ofs; //2,创建一个输出流对象
ofs.open("test.txt", ios::out); //3,打开一个文件,第一个参数是文件路径,不加路径就是当前cpp所在路径,第二个参数是打开方式
ofs << "name: 张三" << endl; //4,写数据
ofs << "age: 18" << endl;
ofs << "sex: 男" << endl;
ofs.close(); //5,关闭流
system("pause");
return 1;
}
打开方式,上述流程中open函数的第二个参数
ios::in //为读文件而打开文件
ios::out //为写文件而打开文件
ios::ate //初始位置:文件末尾
ios::app //追加方式写文件
ios::trunc //如果文件存在,先删除,再创建
ios::binary //二进制方式
文件打开方式可以配合使用,使用|操作符,例如:
ios::in | ios::binary //二进制方式读文件
二,读文件
#include <iostream>
#include <string>
#include <fstream> //1,包含头文件
using namespace std;
int main() {
ifstream ifs; //2,创建一个输入流对象
ifs.open("test.txt", ios::in); //3,打开一个文件,第一个参数是文件路径,不加路径就是当前cpp所在路径,第二个参数是打开方式
if(!ifs.is_open()){ //使用is_open()函数判断是否打开成功
cout << "打开文件失败" << endl;
return;
}
//读取方式一:
char buf[1024] = {0};
while(ifs >> buf){
cout << buf << endl;
}
//读取方式二:第二个参数是指本次操作最多可以读取多少个字节
char buf[1024] = {0};
while(ifs.getline(buf, sizeof(buf))){
cout << buf << endl;
}
//读取方式三:
string buf;
while(getline(ifs, buf)){
cout << buf << endl;
}
//读取方式四:逐个字符地读,EOF:end of file表示文件末尾
char c;
while((c = ifs.get())!= EOF){
cout << c;
}
ifs.close(); //5,关闭流
system("pause");
return 1;
}
三,二进制写文件
ofstream::write()函数
class Person{
public:
char name[64];
int age;
}
int main(){
ofstream ofs("person.txt", ios::out | ios::binary);
Person p = {"张三", 18};
ofs.write((const char*)&p, sizeof(p)); //自定义类型写入,类似序列化
ofs.close();
return 1;
}
四,二进制读文件
ifstream::read()函数
class Person{
public:
char name[64];
int age;
}
int main(){
ifstream ofs("person.txt", ios::in | ios::binary);
if(!ofs.is_open()){
cout << "文件打开失败" << endl;
return;
}
Person p
ifs.read((char*)&p, sizeof(Person)); //自定义类型读出,类似反序列化,第一个参数表示读出来放在哪,第二个参数表示读多长
cout << "姓名: " << p.name << " 年龄: " << p.age << endl; //检验一下是否读取成功
ifs.close();
return 1;
}
注意:
读文件时,可以使用
ifs.eof() 函数判断是否已经到文件末尾,如果要判断是不是个空文件,可以这样用:
这里暂时还不理解为什么要读取一个字符再判断是否eof,判断的时候还是用ifs而不是ch判断的啊,应该与eof的机制有关吧。
ifs.open(FILENAME, ios:in);
char ch;
ifs >> ch;
if(ifs.eof()){
//文件为空
}