002
23.04.2004, 10:03 Uhr
(un)wissender
Niveauwart
|
Vielleicht hilft dir das...
C++: |
#include <iostream> #include <fstream> #include <vector>
class DB { public: DB(const char * fileName = 0); friend std::istream & operator>>(std::istream &in, DB &db); friend std::ostream & operator<<(std::ostream &out, const DB &db); //Zum lesen const int& operator[](size_t index) const; //Zum schreiben void addElementAt(size_t index, int element); private: std::vector<int> storage; };
DB::DB(const char * fileName) { if(fileName) { std::ifstream in(fileName, std::ios::binary | std::ios::in); in >> *this; in.close(); } }
void DB::addElementAt(size_t index, int element) { if(storage.size() <= index) { storage.resize(index + 1); } storage[index] = element; }
const int& DB::operator[](size_t index) const { return storage[index]; }
std::istream & operator>>(std::istream &in, DB &db) { int element; if(in) in.read(reinterpret_cast<char *>(&element), sizeof(int)); for(unsigned int i = 0; in; ++i) { db.addElementAt(i, element); in.read(reinterpret_cast<char *>(&element), sizeof(int)); } return in; }
std::ostream & operator<<(std::ostream &out, const DB &db) { typedef std::vector<int>::const_iterator vecIter; for(vecIter i = db.storage.begin(), end = db.storage.end(); i != end; ++i) { out.write(reinterpret_cast<const char *>(&*i), sizeof(int)); } return out; }
int main(int argc, char *args[]) { if(argc > 2) { std::ofstream out(args[1], std::ios::binary | std::ios::out); int testValues[] = { 11, 12, 13, 345}; int testValuesLength = 4; out.write(reinterpret_cast<const char *>(&testValues[0]), testValuesLength * sizeof(int)); out.close(); DB db(args[1]); std::ofstream outResult(args[2], std::ios::binary | std::ios::out); outResult << db; outResult.close(); } return 0; }
|
-- Wer früher stirbt ist länger tot. Dieser Post wurde am 23.04.2004 um 11:18 Uhr von Pablo editiert. |