【C++】文件操作

文件可以将数据持久化,而不是程序一结束数据就会释放。

文件分为两类:

文本文件:阿斯克码形式存储

二进制文件:二进制形式存储,用户不能直接读


操作文件的头文件

写操作类类型:ofstream

读操作类类型:ifstream

读写操作类类型:fstream


读写文件的三步:打开文件,操作文件,关闭文件

文本文件

写文件

ofstream ofs;//创建对象
ofs.open("文件路径",打开方式);//打开文件
ofs<<"写数据";//操作文件
ofs.close();//关闭文件
【C++】文件操作_第1张图片

如果用两种方式打开文件,需要用|

#include
#include
using namespace std;
int main()
{
    ofstream ofs;
    ofs.open("test.txt",ios::out);//打开
    ofs<<"姓名:张三"<

读文件

#include
#include
#include
using namespace std;
int main()
{
    ifstream ifs;
    ifs.open("test.txt",ios::in);
    if(!ifs.is_open())return 1;
    //操作文件
//方法一
    char buf[1024]={0};
    while(ifs>>buf)
    {cout<

二进制文件

写文件

打开方式要指定为ios::binary

写文件write

ostream& write(const char*buffer,int len);

#include
#include
#include
using namespace std;
class Person
{
public:
    char m_Name[20];
    int m_age;
}
int main()
{
    ofstream ofs("person.txt",ios::out|ios::binary);
    Person p = {"张三“,18};
    ofs.write((const char*)&p,sizeof(Person));
    ofs.close(); 
}

读文件

用read

函数原型:istream& read(char*buffer,int len);

#include
#include
#include
using namespace std;
class Person
{
public:
    char m_Name[20];
    int m_age;
}
int main()
{
    ifstream ifs;
    ifs.open("person.txt",ios::in|ios::binary);
    if(!ifs.is_open())return 1;
    Person p;
    ifs.read((char*)&p,sizeof(Person));
    cout<<"姓名: "<

你可能感兴趣的:(C++,c++,开发语言)