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;
}
}
}
#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;
}
}
}
相关文章推荐
- C++平台相关宏
- C++文件读写详解(ofstream,ifstream,fstream)
- C语言函数指针
- 字符串的next特征函数,KMP算法,C++
- 关于C++构造函数一二
- 详解可变参数列表
- C++文本文件的读写
- C/C++ 常见编译错误及解决办法
- C语言指针-------通过调用函数,完成两个数值的交换
- c++文件流操作
- C++中Static作用和使用方法
- c++类的拷贝构造函数、隐式转换、重载的赋值操作符的一些分析和实例
- [C++]关于STL慎重选择删除元素的方法
- 友元类
- leetcode_226_Invert Binary Tree(C++)(easy)
- Java内联函数(华为面试)-java可能比c++更快
- c语言随机数
- [C++11]新特性——引入了nullptr
- 在C++中子类继承和调用父类的构造函数方法
- 在vc++工程中只使用tlb文件的用法