c++文件读写总结
2011-11-28 14:56
267 查看
#ifndef _FILE_READ_WRITE_H_
#define _FILE_READ_WRITE_H_
#include <fstream>
//some global functions
//read some value according to type
template<typename T>
bool ReadFrom(T& value, std::istream& f)
{
if (f.good())
{
f.read((char*)&value, sizeof(T));
if (sizeof(T) == f.gcount())
return true;
}
return false;
}
template<typename T>
bool ReadFrom(T* value, int count, std::istream& f)
{
if (f.good())
{
f.read((char*)value, sizeof(T) * count);
if (count* sizeof(T) == f.gcount())
return true;
}
return false;
}
template<typename T>
T ReadFromConvert(int bytes, std::istream& f)
{
T val(0);
if (f.good())
{
vector<char> buff;
buff.assign(bytes, 0);
f.read(&buff[0], bytes);
if (bytes == f.gcount())
{
memcpy(&val, &buff[0], bytes);
}
}
return val;
}
template<typename T>
bool WriteTo(T& value, std::ostream& f)
{
if (f.good())
{
f.write((char*)&value, sizeof(T));
return f.good();
}
return false;
}
template<typename T>
bool WriteTo(const T* value, int count, std::ostream& f)
{
if (f.good())
{
f.write((char*)value, sizeof(T)*count);
return f.good();
}
return false;
}
/************************************************************************/
/* Gobal functions */
/************************************************************************/
#include <sstream>
template<typename T>
T Conver2T(const char* str)
{
T valuet;
istringstream istr(str);
istr >> valuet;
return valuet;
}
#endif //end of _FILE_READ_WRITE_H_
#define _FILE_READ_WRITE_H_
#include <fstream>
//some global functions
//read some value according to type
template<typename T>
bool ReadFrom(T& value, std::istream& f)
{
if (f.good())
{
f.read((char*)&value, sizeof(T));
if (sizeof(T) == f.gcount())
return true;
}
return false;
}
template<typename T>
bool ReadFrom(T* value, int count, std::istream& f)
{
if (f.good())
{
f.read((char*)value, sizeof(T) * count);
if (count* sizeof(T) == f.gcount())
return true;
}
return false;
}
template<typename T>
T ReadFromConvert(int bytes, std::istream& f)
{
T val(0);
if (f.good())
{
vector<char> buff;
buff.assign(bytes, 0);
f.read(&buff[0], bytes);
if (bytes == f.gcount())
{
memcpy(&val, &buff[0], bytes);
}
}
return val;
}
template<typename T>
bool WriteTo(T& value, std::ostream& f)
{
if (f.good())
{
f.write((char*)&value, sizeof(T));
return f.good();
}
return false;
}
template<typename T>
bool WriteTo(const T* value, int count, std::ostream& f)
{
if (f.good())
{
f.write((char*)value, sizeof(T)*count);
return f.good();
}
return false;
}
/************************************************************************/
/* Gobal functions */
/************************************************************************/
#include <sstream>
template<typename T>
T Conver2T(const char* str)
{
T valuet;
istringstream istr(str);
istr >> valuet;
return valuet;
}
#endif //end of _FILE_READ_WRITE_H_