Code:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
typedef unsigned char byte;
const int BLOCKSIZE=512;
const int Nb=3;
struct Customer {
char id[8];
char fname[13];
char lname[21];
char street[13];
unsigned int postcode;
unsigned short number;
char type;
};
struct Code {
unsigned short int postcode;
char city[14];
};
class MyCompare {
public:
int operator()(const Code& c1,const Code& c2) const {
return c1.postcode<c2.postcode;
}
};
// Gets the length bytes from Block starting from offset putting them in value
void getField(byte* Block,int length,int offset,void* value) {
Block+=offset;
memcpy(value,Block,length);
}
// Sets the length bytes from Block starting from offset into value
void setField(byte *Block,int length,int offset,void *value) {
Block+=offset;
memcpy(Block,value,length);
}
void sortfile(ifstream& infile,int recsize,int field,fstream& outfile) {
byte* block=new byte[BLOCKSIZE];
int recnum=BLOCKSIZE/recsize;
infile.seekg(0,ios::end);
int blocknum=int(ceil(float(infile.tellg())/float(BLOCKSIZE)));
infile.seekg(0,ios::beg);
// int Nr=int(ceil(float(blocknum)/float(Nb)));
int i=1;
while(!infile.eof()) {
vector<Code> code;
for(int j=1;j<=recnum*Nb;j++) {
Code tmpcode;
infile>>tmpcode.postcode>>tmpcode.city;
if(infile.eof()) break;
code.push_back(tmpcode);
}
sort(code.begin(),code.end(),MyCompare());
string name(1,char(48+i));name="code"+name;
fstream run(name.c_str(),ios::binary|ios::out|ios::in|ios::trunc);
for(int j=0;j<int(ceil(float(code.size())/float(recnum)));j++) {
for(int k=0;k<recnum && j*recnum+k<code.size();k++) {
setField(block,2,k*recsize,&code[j*recnum+k].postcode);
setField(block,14,k*recsize+2,code[j*recnum+k].city);
}
run.write(block,BLOCKSIZE); // *********
memset(block,0,BLOCKSIZE);
}
i++;
}
ifstream in1("code1");
for(int j=0;j<3;j++) {
in1.read(block,BLOCKSIZE); // ****************
for(int i=0;i<32;i++) {
int postcode;char city[14];
getField(block,2,i*recsize,&postcode);
getField(block,14,i*recsize+2,city);
cout<<postcode<<' '<<city<<endl; // $$$$$$$$$$$
}
}
ifstream in2("code2");
in2.read(block,BLOCKSIZE); // *****************
for(int i=0;i<2;i++) {
int postcode;char city[14];
getField(block,2,i*recsize,&postcode);
getField(block,14,i*recsize+2,city);
cout<<postcode<<' '<<city<<endl; // $$$$$$$$$$
}
delete[](block);
}
int main(int argc,char** argv) {
if(argc!=4) {
cout<<"Usage:as1 <customer_file> <code_file> <city>"<<endl;
exit(1);
}
ifstream custfile(argv[1]);
if(!custfile) {
cout<<"Could not open file "<<argv[1]<<endl;
exit(1);
}
ifstream codefile(argv[2]);
if(!codefile) {
cout<<"Could not open file "<<argv[2]<<endl;
exit(1);
}
string city=argv[3];
fstream outfile("test21ord",ios::binary|ios::out|ios::in|ios::trunc);
sortfile(codefile,sizeof(Code),6,outfile);
}
In Linux it runs perfectly.