• 读写二进制文件


    #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;
    }

  • 相关阅读:
    去除安卓apk中的广告
    公司固定资产管理细则
    固定资产基础知识
    C#的WebBrowser操作frame
    C#程序集版本控制文件属性祥解
    c#使用RSA进行注册码验证
    Web前端开发十日谈
    Web.xml配置详解
    IBM WebSphere MQ的C#工具类以及源码(net)
    Castle IOC FOR MVC 使用方法
  • 原文地址:https://www.cnblogs.com/jck34/p/2713641.html
Copyright © 2020-2023  润新知