zoukankan      html  css  js  c++  java
  • c++文件读写

    先上一张镇楼图

    再来一个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
    ";
        writer << 100 << "
    ";
        writer << "third line
    ";
        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/

  • 相关阅读:
    Codeforces
    Codeforces
    Codeforces
    Codeforces
    Codeforces
    Codeforces
    Codeforces
    Codeforces
    洛谷
    GXU
  • 原文地址:https://www.cnblogs.com/gattaca/p/7299823.html
Copyright © 2011-2022 走看看