您的位置:首页 > 编程语言 > C语言/C++

C++二进制文件的读写

2016-04-18 14:11 363 查看
#include <iostream>

#include "math.h"

#include <cstdlib>

#include <fstream>

#include <iomanip>

using namespace std;

void sort(int [], int);

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char** argv) {

fstream dat, out;

int i,a[20],b[20]; //定义文件流对象

dat.open("d:\\file.dat", ios::binary|ios::out|ios::in); //为读写打开二进制文件

// cout<<"data"<<dat<<endl;

if(!dat){

cout<<"cannot open file"<<endl;

exit(0);

}

for(i=0; i<20; i++){

a[i] = rand();

dat.write((char*)&a[i], sizeof(int)); //将20个数写入文件

}

dat.seekg(0);

for(i=0; i<20; i++){

dat.read((char*)&b[i],sizeof(int)); //读出20个数

}

sort(b, 20);

out.open("file.out", ios::out); //为输出打开文本文件

if(!out){

cout<<"cannot open file"<<endl;

exit(0);

}

for(i=0; i<20; i++){ //将排序后数据写入文本文件

out<<b[i]<<' ';

}

out<<endl;

for(i=0; i<20; i++){

cout<<setw(10)<<b[i];

if((i+1)%5==0) cout<<endl;

}

out.close(); //关闭文件

dat.close();

return 0;

}

void sort(int x[], int m){ //排序函数

int i,j,k,t;

for(i=0; i<m-1; i++){

k = i;

for(j=i+1; j<m; j++){

if(x[j]<x[k]) k = j;

}

if(k!=j){

t = x[i];

x[i] = x[k];

x[k] = t;

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: