求有VC6的朋友帮忙运行一个简单程序

来源:百度知道 编辑:UC知道 时间:2024/06/08 04:20:01
范例:建立一个应用程序,包括数据输入,存盘,读盘,操作数据后存储.通过随机数函数rand()产生20个整数,逐个将这些数以二进制方式写入文件file.dat中.然后读出这些数,在内存中对它们进行增序排序,再将排序后的数以文本方式逐个写入file.out文件中.
[程序] 用C++的文件流进行文件管理,用流类的函数进行文件读写.

程序
#include //可以不写
#include
#include
using namespace std;
const int n=20;
void sort(int [],int);
int main(){
fstream dat, out; //定义文件流对象
int i,a[n],b[n];
dat.open("file.dat",ios::out|ios::in|ios::binary);//为读写打开二进制文件
if(!dat){ //文件不存在
dat.clear(0); //清状态字
dat.open("file.dat",ios::out|ios::binary);//文件不存在,建立二进制文件
dat.close();
dat.open("file.dat",ios::out|ios::in|ios::binary);//为读写打开二进制文件
if(!dat){
cout<<"cannot open file\n";
return -1;
}
}
for(i=0;i a[i]=rand();
dat.write((char*)&a[i],sizeof(int));//将20个数写入文件
}//因文件打开时,文件指针在头部,所以该操作是刷新文件
dat.seekg(0); //将文件指针移至文件头
for(i=0;i dat.read((char*)&b[i],sizeof(int));//读出20个数
}
sort(b,n

以下是修改后正确的程序:

#include <iostream>//可以不写
#include <string>
#include <fstream>
using namespace std;
const int n=20;
void sort(int [],int);
int main(){
fstream dat, out; //定义文件流对象
int i,a[n],b[n];
char buff[10];
dat.open("file.dat",ios::out|ios::in|ios::binary);//为读写打开二进制文件
if(!dat){ //文件不存在
dat.clear(0); //清状态字
dat.open("file.dat",ios::out|ios::binary);//文件不存在,建立二进制文件
dat.close();
dat.open("file.dat",ios::out|ios::in|ios::binary);//为读写打开二进制文件
if(!dat){
cout<<"cannot open file\n";
return -1;
}
}
for(i=0;i < n; i++)
{
a[i]=rand();
memset(buff,'\0',sizeof(buff));
itoa(a[i],buff,10);
dat.write(buff,sizeof(buff));//将20个数写入文件
}//因文件打开时,文件指针在头部,所以该操作是刷新文件
dat.seekg(0); //将文件指针移至文件头
for(i=0;i < n; i++)
{
dat.read(buff,si