c++文件读写

博客展示了一张镇楼图和一个C/C++的demo,还提供了C++标准库中sscanf函数的参考链接http://www.cplusplus.com/reference/cstdio/sscanf/,以及一篇相关文章的转载链接https://www.cnblogs.com/gattaca/p/7299823.html。

先上一张镇楼图

再来一个demo

#include <iostream>
#include <fstream>
#include <string>

#define BUFFER_SIZE 128

using namespace std;

struct Person
{
    string name = "xiaoming";
    int age = 18;
    bool isHe = false;
};

int main()
{
    ofstream writer("test.txt");
    
    if (!writer.is_open()) {
        cout << "ofstream open file failed" << endl;
        return 1;
    }
    
    writer << "first line\n";
    writer << 100 << "\n";
    writer << "third line\n";
    writer << "fourth line";
    
    writer.close();
    
    ifstream reader("test.txt");
    
    char buffer[BUFFER_SIZE];
    while (reader.getline(buffer, BUFFER_SIZE)) {
        cout << "current line: " << buffer << endl;
    }
    
    reader.close();
    cout << "read done" << endl;
    
    writer.open("test.bin", ios::binary);
    
    Person daming;
    daming.name = "daming";
    daming.age = 28;
    daming.isHe = true;
    
    writer.write((char*)&daming, sizeof(struct Person));
    writer.close();
    
    reader.open("test.bin", ios::binary);
    
    Person target;
    reader.read((char*)&target, sizeof(struct Person));
    
    cout << target.name << endl;
    cout << target.age << endl;
    cout << target.isHe << endl;
    
    cout << "read done" << endl;
}

 

PS:

http://www.cplusplus.com/reference/cstdio/sscanf/

转载于:https://www.cnblogs.com/gattaca/p/7299823.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值