C++22/03/17

#include <iostream>
using namespace std;
#include <string>
//文件操作
//写文件 ofs  out把数据放到文件  
//读文件 ifs  in把文件数据放到自己准备好的地方
#include <fstream>//头文件
//写文件
void test()
{
    //添加头文件
    //创建流对象
    ofstream ofs;//out file   写文件
    //指定打开方式
    ofs.open("test.txt", ios::out);
    //写
    ofs << "123456789" << endl;
    ofs << "123456789" << endl;
    ofs << "123456789" << endl;
    ofs << "123456789" << endl;
    //关闭文件
    ofs.close();


}

int main()
{
    test();
}




#include <iostream>
using namespace std;
#include <string>
//文件操作
#include <fstream>//头文件
//读文件
void test1()
{
    //创建流对象
    ifstream ifs;
    //指定打开方式
    ifs.open("test.txt", ios::in);
    //判断打开是否成功
    if (!ifs.is_open())
    {
        cout << "defest" << endl;
        return;//程序到此结束
    }
    //读取
    //方式1
    /* char buf[1024] = {0};
    while (ifs >> buf)  //碰到空格会直接换行
    {
        cout << buf << endl;
    } */
    //方式2
    /* char buf[1024] = {0};
    while (ifs.getline(buf, sizeof(buf)))
    {
        cout << buf << endl;
    } */
    //方式3
    string buf;//推荐
    while (getline(ifs, buf))//ifs:流对象   buf:准备好的字符串
    {
        cout << buf << endl;
    }
    ifs.close();
}
int main()
{
    test1();
}



#include <iostream>
using namespace std;
#include <string>
//文件操作
#include <fstream>//头文件
//二进制
//写二进制
class person
{
public:
    int m_age;
    char m_name[64];
};
void test()
{
    ofstream ofs("person.txt", ios::out | ios::binary);
    //ofs.open("person.txt",ios::out|ios::binary);
    person p = {18,"abc"};
    ofs.write((const char*)&p,sizeof(person));
    ofs.close();
}
int main()
{
    test();
    
}



#include <iostream>
using namespace std;
#include <string>
//文件操作
#include <fstream>//头文件
//读二进制
class person
{
public:
    int age;
    char m_name[64];
};
void test()
{
    ifstream ifs;
    ifs.open("person.txt", ios::in | ios::binary);
    if (!ifs.is_open())
    {
        cout << "defeat" << endl;
        return;
    }
    person p;
    ifs.read((char*)&p, sizeof(person));
    cout << p.age << p.m_name << endl;
    ifs.close();
}
int main()
{
    test();
    
}







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值