Problem L7_F3_Z1
Write a program that reverses the order of integers stored in a binary file L7_F3_Z1.dat. Do not use
additional files.
#include<cstdio>
#include<fstream>
#include<iomanip>
#include<iostream>
using namespace std;
//Ö®ËůŇÔgcountĘäłö10Ćäʵ˛»ĘÇ10Ł¬ĆäʵĘÇ16.ŇňÎŞµ±ÓĂŐâ¸ölen×÷forŃ»·µÄʱşňĆäʵĘÇ16
int main(){
ifstream ifs("L8_F3_Z1.dat",ios::binary);
if(!ifs){
cout<<"Error opening file\n";
return 1;
}
int len;
unsigned char txt[100][4];
int number[1000];
int count=0;
cout<<sizeof(int)<<endl;
string sentence;
ifs.seekg(0,ios::end);
cout<<"The whole chars of this file is "<<ifs.tellg()<<endl;
//×îşóÍęłÉÖ»ĘǸÄÁËŐâŔď¶řŇŃŁ¬ĆäʵҲûÓĐ×öʲôŁ¬żÉÄÜľÍĘÇÓď·¨µÄÉčÖĂÎĘĚâ°É
len=ifs.tellg()/4;
ifs.seekg(0,ios::beg);
while(count<len){//!ifs means what
ifs.read(reinterpret_cast<char*>(&txt[count]),sizeof(int));//˝«¶Áȡµ˝µÄĘýÇżÖĆת»»łÉcharĐÍŁ¬ŇňÎŞŐâ¸ötxtĘÇcharĐÍÖ¸Őë
cout<<"txt:"<<txt[count]<<endl;
cout<<"txt1:"<<setfill('0')<<setw(2)<<hex<<static_cast<int>(txt[count][1]-'0')<<":";
cout<<"txt2:"<<setfill('0')<<setw(2)<<hex<<static_cast<int>(txt[count][2]-'0')<<":";
cout<<"txt3:"<<setfill('0')<<setw(2)<<hex<<static_cast<int>(txt[count][3]-'0')<<":";
cout<<"txt4:"<<setfill('0')<<setw(2)<<hex<<static_cast<int>(txt[count][4]-'0')<<endl;
// int txt1=(txt[1]-'0')<<12;
// int txt2=(txt[2]-'0')<<8;
// int txt3=(txt[3]-'0')<<4;
// int txt4=txt[4]-'0';
// number[count]=txt1+txt2+txt3+txt4;
// cout<<number[count]<<endl;
count++;
}
cout<<count<<endl;
ifs.close();
//before open it, clear all
ofstream ofs("L8_F3_Z1.dat",ios::binary|ios::out|ios::trunc);
if(!ofs){
cout<<"Error opening file\n";
return 1;
}
ofs.seekp(0,ios::end);
int nowPosition=ofs.tellp();
cout<<"The position now is "<<nowPosition<<endl;
ofs.seekp(0,ios::beg);
for(int i=0;i<count;i++){
ofs.seekp(i*4,ios::beg);
ofs.write(reinterpret_cast<char*>(&txt[count-i-1]), sizeof(int));
}
ofs.close();
return 0;
}