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

    #include <cstdlib>
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <iomanip>
    
    using namespace std;
    
    /*
     * 
     */
    inline void eatline() {while(cin.get() != '\n') continue;}
    struct planet{
        char name[20];
        double population;
        double g;
    };
    
    const char *file = "planets.dat";
    int main(int argc, char** argv) {
    
        planet pl;
        cout<<fixed<<right;
        ifstream fin;
        fin.open(file,ios_base::in | ios_base::binary);
        if(fin.is_open())
        {
            cout<<"Here are the contents of "<<file<<" file: \n";
            while(fin.read((char*)&pl,sizeof(pl)))
            {
                cout<<setw(20)<<pl.name<<": "
                    <<setprecision(0)<<setw(12)<<pl.population
                    <<setprecision(2)<<setw(6)<<pl.g<<endl;
            }
            fin.close();
        }
        
        ofstream fout(file,ios_base::out | ios_base::app | ios_base::binary);
        if(!fout.is_open())
        {
            cerr<<"Can`t open "<<file<<" file for output; \n";
            exit(EXIT_FAILURE);
        }
        cout<<"Enter planet name (enter a blank to quit): \n";
        cin.get(pl.name,20);
        while(pl.name[0] != '\0')
        {
            eatline();
            cout<<"Enter planetary population: ";
            cin>>pl.population;
            cout<<"Enter planet`s acceleration of gravity: ";
            cin>>pl.g; 
            eatline();
            fout.write((char*)&pl,sizeof pl);
            cout<<"Enter planet name (enter a blank to quit): \n";
            cin.get(pl.name,20);
        }
        fout.close();
        
        fin.clear();
        fin.open(file,ios_base::in | ios_base::binary);
        if(fin.is_open())
        {
            cout<<"Here are the new contents of the "<<file<<" file: \n";
            while(fin.read((char*)&pl,sizeof pl))
            {
                cout<<setw(20)<<pl.name<<": "
                    <<setprecision(0)<<setw(12)<<pl.population
                    <<setprecision(2)<<setw(6)<<pl.g<<endl;
            }
            fin.close();
        }
        return 0;
    }

  • 相关阅读:
    449. 序列化和反序列化二叉搜索树
    极客mysql08
    极客mysql06
    MySQL死锁问题(转)
    mysql一些好的问题
    如何在Ubuntu 20.04 LTS Focal Fossa上安装Dokuwiki
    在Ubuntu 20.04 LTS Focal Fossa上安装Icinga
    如何在Ubuntu 20.04 LTS Focal Fossa服务器上安装PowerShell
    如何在CentOS 8服务器上安装Discord
    在CentOS 8服务器上安装Apache Solr搜索平台
  • 原文地址:https://www.cnblogs.com/jck34/p/2713641.html
Copyright © 2011-2022 走看看