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;
}
相关推荐
MC皮蛋侠客5 小时前
Google Test 单元测试指南
c++·单元测试·google test
方也_arkling6 小时前
【Java-Day08】static / final / 枚举
java·开发语言
艾莉丝努力练剑6 小时前
【Linux:文件】Ext系列文件系统进阶
linux·运维·服务器·c++·文件系统·文件io·ext
风吹夏回6 小时前
Python 全局异常处理:从“满屏 try-except”到优雅兜底
开发语言·python
Chengbei116 小时前
一站式源码安全检测工具、云安全 / APP / 小程序源码敏感信息递归多层目录扫描AK、JWT、手机号、身份证等敏感信息
java·开发语言·安全·web安全·网络安全·系统安全·安全架构
llz_1126 小时前
web-第一次课后作业
java·开发语言·idea
小熊Coding7 小时前
Python爬取当当网二手图书项目实战!
开发语言·爬虫·python·beautifulsoup·requests·二手图书
秋97 小时前
Java项目运行5天左右自动宕机:系统性定位与解决方案
java·开发语言·python
xiaoshuaishuai87 小时前
C# 内存管理与资源泄漏
开发语言·c#
lsx2024067 小时前
SVN 检出操作
开发语言