导航:
1.文件类型,打开方式
2.文本文件或者二进制读写操作
3.注意点
———————————————————————————————————
文件类型:
文本文件-以文类ASCII形式存储
二进制文件-二进制形式
创建流对象有三种方式:
ofstream——进行写操作
ifstream——进行读操作
fstream——进行读写操作
写文件大致过程:
1.头文件
#include <fstream>
2.创建流对象
ofstream ofs;
3.打开方式
ofs.open("文件路径",打开方式)
4.写入
ofs<<你要写的内容
5.关闭文件
ofs.close();
———————————————————————————————————
读文件大致过程
1.头文件
#include <fstream>
2.创建流对象
ifstrean ifs;
3.打开方式;判断是否打开文件
ifs.open("打开路径",打开方式) if(!ifs.is_open()) { cout<<"打开文件失败"<<endl; }
4.读数据
有4种读取方式,见下文
5.关闭文件
ifs.close();
打开方式:
ios::in 为读文件而打开文件
ios::out 为写文件而打开文件
ios::ate 初始位置:文件尾
ios:app 追加方式写
ios::tranc 文件存在删除再建
ios::binary 二进制方式(读写二进制要用的)
———————————————————————————————————
注意:若要进行二进制写文件,要加一个|,例如:ios::binary | ios::out (步骤3中的打开方式)
文本文件写操作:
#include <iostream> #include <fstream> #include <string> using namespace std; int main() { //1.包含头文件 //2.创建流 ofstream ofs; //3.打开方式 ofs.open("test.txt",ios::out); //进行写操作而打开文件 //4.读入 ofs<<"姓名:张三"<<endl; //5.关闭文件 ofs.close(); system("pause"); }
文本文件读操作:
#include <iostream> #include <fstream> #include <string> using namespace std; int main() { //创建流对象 ifstream ifs; //打开方式 ifs.open("test.txt",ios::in); if(!ifs.is_open()) { cout<<"文件打开失败"<<endl; } //写入数据 /*第一种 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; }*/ //第四种 char c; while((c = ifs.get()) != EOF ) { cout<<c; } //关闭文件 ifs.close(); system("pause"); }
包含四种操作进行读
二进制文件写操作:
#include <iostream> #include <fstream> #include <string> using namespace std; class Person { public: char name[1024]; //尽量用数组来写 int age; }; int main() { //1.包含头文件 Person p = {"张三",18}; //2.创建流 ofstream ofs("person.txt",ios::out |ios::binary); //3.打开方式 //ofs.open("person.txt",ios::out |ios::binary); //4.写入 ofs.write((const char *)&p,sizeof(p)); //5.关闭文件 ofs.close(); system("pause"); }
二进制文件读操作:
#include <iostream> #include <fstream> #include <string> using namespace std; class Person { public: char name[1024]; //尽量用数组来写 int age; }; int main() { //1.包含头文件 Person p = {"张三",18}; //2.创建流 ofstream ofs("person.txt",ios::out |ios::binary); //3.打开方式 //ofs.open("person.txt",ios::out |ios::binary); //4.写入 ofs.write((const char *)&p,sizeof(p)); //5.关闭文件 ofs.close(); system("pause"); }
注意点:
1.读文件时要判断是否文件存在
2.读写方式若是二进制时,打开方式要加上| ios::binary
3.进行二进制写文件中尽量用数组进行保存数据,再写入