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

  • 相关阅读:
    自定义simple_tag
    测试流程规范系列(2):测试计划
    测试流程规范系列(4):测试准入
    测试流程规范系列(3):测试用例
    测试流程规范系列(1):测试流程
    Jmeter系列(1):安装
    Jmeter系列(2):简介
    Jmeter系列(3):使用
    Jmeter系列(4):插件
    Jmeter系列(5):参数化
  • 原文地址:https://www.cnblogs.com/jck34/p/2713641.html
Copyright © 2011-2022 走看看