Day13-C++基础之文件操作

文件操作

复制代码
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
​
class Person{
public:
    char m_Name[64];
    int m_Age;
};
​
int main(){
    //文本文件操作
​
    //写文件
    //1.包含头文件 fstream
    //2.创建流对象
    ofstream ofs;
    //3.指定打开方式
    ofs.open("test.txt",ios::out);//不指定路径会创建在项目文件夹下
    //这里注意:读文件打开方式:ios::in
    //写文件打开方式:ios::out
    //追加方式写文件:ios:app
    //如果文件存在就先删除再创建:ios::trunc
    //二进制方式:ios::binary
    //4.写内容
    ofs<<"name"<<endl;
    ofs<<"Jason"<<endl;
    //5.关闭文件
    ofs.close();
​
    //读文件
    //1.头文件
    //2.创建流对象
    ifstream ifs;
    //3.打开文件,并判断是否打开成功
    ifs.open("test.txt",ios::in);
    if(!ifs.is_open()){
        cout<<"fail to open"<<endl;
        return 0;
    }
    //4.读数据
    char buf[1024]={0};
    while(ifs>>buf){
        cout<<buf<<endl;
    }
    //或者
    char buf1[1024]={0};
    while(ifs.getline(buf,sizeof(buf))){
        cout<<buf<<endl;
    }
    //或者
    string buf2;
    while(getline(ifs,buf2)){
        cout<<buf<<endl;
    }
    //或者
    char c;
    while((c=ifs.get())!=EOF){
        cout<<c;
    }
    //5.关闭文件
    ifs.close();
​
    //二进制文件
    //写文件
    ofstream ofs1;
    ofs1.open("person.txt",ios::out|ios::binary);
    Person p={"Jason",18};
    ofs1.write((const char*)&p,sizeof(Person));//这里将Person类型强转为char
    ofs1.close();
​
    //读文件
    ifstream ifs1;
    ifs1.open("person.txt",ios::in|ios::binary);
    if(!ifs1.is_open()){
        cout<<"文件打开失败"<<endl;
        return 0;
    }
    Person p1;
    ifs1.read((char*)&p,sizeof(Person));
    ifs1.close();
​
    return 0;
}
相关推荐
不想写代码的星星16 分钟前
C++继承、组合、聚合:选错了是屎山,选对了是神器
c++
不想写代码的星星1 天前
std::function 详解:用法、原理与现代 C++ 最佳实践
c++
樱木Plus3 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
blasit5 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_6 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星6 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛8 天前
delete又未完全delete
c++
端平入洛9 天前
auto有时不auto
c++
郑州光合科技余经理10 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo12310 天前
matlab画图工具
开发语言·matlab