home *** CD-ROM | disk | FTP | other *** search
- /*
- C++ program that demonstrates random-access binary file I/O
- */
-
- #include <iostream.h>
- #include <fstream.h>
- #include <stdlib.h>
- #include <string.h>
-
- const unsigned MIN_SIZE = 5;
- const unsigned STR_SIZE = 31;
- const double BAD_VALUE = -1.0e+30;
- enum boolean { false, true };
-
- class VmArray
- {
- protected:
- fstream f;
- unsigned size;
- double badIndex;
-
- public:
- VmArray(unsigned Size, const char* filename);
- ~VmArray()
- { f.close(); }
- unsigned getSize() const
- { return size; }
- boolean writeElem(const char* str, unsigned index);
- boolean readElem(char* str, unsigned index);
- void Combsort();
- };
-
- VmArray::VmArray(unsigned Size, const char* filename)
- {
- char s[STR_SIZE+1];
- size = (Size < MIN_SIZE) ? MIN_SIZE : Size;
- badIndex = BAD_VALUE;
- f.open(filename, ios::in | ios::out | ios::binary);
- if (f.good()) {
- // fill the file stream with empty strings
- strcpy(s, "");;
- f.seekg(0);
- for (unsigned i = 0; i < size; i++)
- f.write((unsigned char*)s, sizeof(s));
- }
- }
-
- boolean VmArray::writeElem(const char* str, unsigned index)
- {
- if (index < size) {
- f.seekg(index * (STR_SIZE+1));
- f.write((unsigned char*)str, (STR_SIZE+1));
- return (f.good()) ? true : false;
- }
- else
- return false;
- }
-
- boolean VmArray::readElem(char* str, unsigned index)
- {
- if (index < size) {
- f.seekg(index * (STR_SIZE+1));
- f.read((unsigned char*)str, (STR_SIZE+1));
- return (f.good()) ? true : false;
- }
- else
- return false;
- }
-
- void VmArray::Combsort()
- {
- unsigned i, j, gap = size;
- boolean inOrder;
- char strI[STR_SIZE+1], strJ[STR_SIZE+1];
-
- do {
- gap = (gap * 8) / 11;
- if (gap < 1)
- gap = 1;
- inOrder = true;
- for (i = 0, j = gap; i < (size - gap); i++, j++) {
- readElem(strI, i);
- readElem(strJ, j);
- if (strcmp(strI, strJ) > 0) {
- inOrder = false;
- writeElem(strI, j);
- writeElem(strJ, i);
- }
- }
- } while (!(inOrder && gap == 1));
- }
-
- main()
- {
- char* data[] = { "Michigan", "California", "Virginia", "Main",
- "New York", "Florida", "Nevada", "Alaska",
- "Ohio", "Maryland" };
- VmArray arr(10, "arr.dat");
- char str[STR_SIZE+1];
- char c;
-
- // assign values to array arr
- for (unsigned i = 0; i < arr.getSize(); i++) {
- strcpy(str, data[i]);
- arr.writeElem(str, i);
- }
- // display unordered array
- cout << "Unsorted arrays is:\n";
- for (i = 0; i < arr.getSize(); i++) {
- arr.readElem(str, i);
- cout << str << "\n";
- }
- // pause
- cout << "\nPress any key and then Return to sort the array...";
- cin >> c;
- // sort the array
- arr.Combsort();
- // display sorted array
- cout << "Sorted arrays is:\n";
- for (i = 0; i < arr.getSize(); i++) {
- arr.readElem(str, i);
- cout << str << "\n";
- }
- return 0;
- }