Er ikke specielt god til c++, men det her er sådan jeg ville gøre det.
#include <iostream>
#include <fstream>
#include <vector>
class FileReader{
private:
char* m_filename;
std::fstream *m_file;
public:
bool openWriteFile(char* a_filename){
m_file=new std::fstream(a_filename, std::ios::out|std::ios::binary|std::ios::trunc);
return m_file->is_open();
}
bool openReadFile(char* a_filename){
m_file=new std::fstream(a_filename, std::ios::in|std::ios::binary);
if(m_file->is_open()){
m_file->seekg(0,std::ios::beg);
return true;
}else{
return false;
}
}
void closeFile(){
m_file->close();
}
template<typename T>
bool read(T& in){
m_file->read((char* )(&in), sizeof(T));
return !m_file->bad();
}
template<typename T>
bool write(T& out){
m_file->write((char* )(&out), sizeof(T));
return !m_file->bad();
}
template<typename T>
bool writeList(std::vector<T>& out){
typedef T value_type;
typedef std::vector<T> list;
typedef typename list::iterator listIt;
int p=out.size();
write(p);
for(listIt i=out.begin();i!=out.end();++i){
write(*i);
}
return !m_file->bad();
}
template<typename T>
bool readList(std::vector<T> &in){
int size;
read(size);
for(int i=0;i<size;i++){
T hold;
read(hold);
in.push_back(hold);
}
return !m_file->bad();
}
};
int main()
{
FileReader f;
if(f.openWriteFile("test.bin")){
int i=1022;
char c='T';
double d=10.0;
char* cc="Test";
std::vector<float> floats;
floats.push_back(1.0);
floats.push_back(2.0);
floats.push_back(3.0);
f.writeList(floats);
f.write(c);
f.write(i);
f.write(d);
f.write(cc);
f.closeFile();
}
if(f.openReadFile("test.bin")){
int i2;
char c2;
double d2;
char* cc2;
std::vector<float> floats2;
f.readList(floats2);
for(std::vector<float>::iterator i=floats2.begin();i!=floats2.end();++i){
std::cout <<(*i)<<" ";
}
std::cout <<std::endl;
f.read(c2);
std::cout <<c2<< std::endl;
f.read(i2);
std::cout <<i2<< std::endl;
f.read(d2);
std::cout <<d2<< std::endl;
f.read(cc2);
std::cout <<cc2<< std::endl;
f.closeFile();
}
return 0;
}
fil formatet er i eksemplet i main functions:
1 vector af floats
1 char
1 integer
1 double
1 char*
Indlæg senest redigeret d. 11.05.2008 17:59 af Bruger #5620