1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
|
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
class Sdisk
{
public :
Sdisk(string diskname);
Sdisk(string diskname, int numberofblocks, int blocksize);
int getblock(int blocknumber, string& buffer);
int putblock(int blocknumber, string buffer);
private :
string diskname; // file name of pseudo-disk
int numberofblocks; // number of blocks on disk
int blocksize; // block size in bytes
};
Sdisk::Sdisk(string discname)
{
if (diskname == discname)
{
fstream iofile;
string disc = diskname + ".spc";
iofile.open(disc.c_str());
iofile >> numberofblocks >> blocksize;
iofile.close();
}
else
{
cout << "No disk exist. Error code 1" << endl;
}
}
Sdisk::Sdisk(string diskname, int numberofblocks, int blocksize) //default constructor
{
/* if (diskname = discname)
{
fstream iofile;
string disc = diskname + ".spc";
iofile.open(disc.c_str());
iofile >> numberofblocks >> blocksize;
iofile.close();
}
else
{
cout << "No disk exist. Error code 1" << endl;
}*/
this -> diskname = diskname;
this -> numberofblocks = numberofblocks;
this -> blocksize = blocksize;
string spcfile = diskname + ".spc";
string datfile = diskname + ".dat";
ofstream outfile;
outfile.open(spcfile.c_str());
outfile << numberofblocks << " " << blocksize;
outfile.close();
outfile.open(datfile.c_str());
for(int i = 0; i < numberofblocks * blocksize; i++)
{
outfile.put('#');
}
long length = outfile.tellp();
cout << "File size is: " << length << endl;
outfile.close();
int Sdisk::getblock(int blocknumber, string& buffer)
{
ifstream enterdat;
string opendat = diskname + ".dat";
enterdat.open(opendat.c_str());
enterdat.seekg(blocksize * blocknumber, ios::beg);
for(int i = 0; i < blocksize; i++)
{
char a = enterdat.get();
buffer += x;
}
enterdat.close();
}
int Sdisk::putblock(int blocknumber, string buffer)
{
ofstream enterdat;
string opendat = diskname + ".dat";
enterdat.open(opendat.c_str(), ios::in | ios::out);
enterdat.seekp(blocksize * blocknumber, ios::beg);
for(int i = 0; i < blocksize; i++)
{
enterdat.put(buffer[i]);
}
enterdat.close();
}
// You can use this to test your Sdisk class
int main()
{
Sdisk disk1("test1",16,32);
string block1, block2, block3, block4;
for (int i=1; i<=32; i++) block1=block1+"1";
for (int i=1; i<=32; i++) block2=block2+"2";
disk1.putblock(4,block1);
disk1.getblock(4,block3);
cout << "Should be 32 1s : ";
cout << block3 << endl;
disk1.putblock(8,block2);
disk1.getblock(8,block4);
cout << "Should be 32 2s : ";
cout << block4 << endl;
}
|