SimpleFile.h
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011 #ifndef __SIMPLEFILE_H__
00012 #define __SIMPLEFILE_H__
00013
00014 #include "lib/io.h"
00015 #include "base/SGObject.h"
00016
00017 #include <stdio.h>
00018 #include <string.h>
00019
00023 template <class T> class CSimpleFile : public CSGObject
00024 {
00025 public:
00032 CSimpleFile(char* fname, FILE* f)
00033 : CSGObject()
00034 {
00035 file=f;
00036 filename=strdup(fname);
00037 status = (file!=NULL && filename!=NULL);
00038 }
00039
00040 ~CSimpleFile() { free(filename); }
00041
00048 T* load(T* target, int64_t& num=0)
00049 {
00050 if (status)
00051 {
00052 status=false;
00053
00054 if (num==0)
00055 {
00056 bool seek_status=true;
00057 int64_t cur_pos=ftell(file);
00058
00059 if (cur_pos!=-1)
00060 {
00061 if (!fseek(file, 0, SEEK_END))
00062 {
00063 if ((num=(int)ftell(file)) != -1)
00064 {
00065 SG_INFO( "file of size %ld bytes == %ld entries detected\n", num,num/sizeof(T));
00066 num/=sizeof(T);
00067 }
00068 else
00069 seek_status=false;
00070 }
00071 else
00072 seek_status=false;
00073 }
00074
00075 if ((fseek(file,cur_pos, SEEK_SET)) == -1)
00076 seek_status=false;
00077
00078 if (!seek_status)
00079 {
00080 SG_ERROR( "filesize autodetection failed\n");
00081 num=0;
00082 return NULL;
00083 }
00084 }
00085
00086 if (num>0)
00087 {
00088 if (!target)
00089 target=new T[num];
00090
00091 if (target)
00092 {
00093 size_t num_read=fread((void*) target, sizeof(T), num, file);
00094 status=((int64_t) num_read == num);
00095
00096 if (!status)
00097 SG_ERROR( "only %ld of %ld entries read. io error\n", (int64_t) num_read, num);
00098 }
00099 else
00100 SG_ERROR( "failed to allocate memory while trying to read %ld entries from file \"s\"\n", (int64_t) num, filename);
00101 }
00102 return target;
00103 }
00104 else
00105 {
00106 num=-1;
00107 return NULL;
00108 }
00109 }
00110
00117 bool save(T* target, int64_t num)
00118 {
00119 if (status)
00120 {
00121 status=false;
00122 if (num>0)
00123 {
00124 if (!target)
00125 target=new T[num];
00126
00127 if (target)
00128 {
00129 status=(fwrite((void*) target, sizeof(T), num, file)==
00130 (size_t) num);
00131 }
00132 }
00133 }
00134 return status;
00135 }
00136
00141 inline bool is_ok() { return status; }
00142
00143 protected:
00145 FILE* file;
00147 bool status;
00149 char task;
00151 char* filename;
00152 };
00153 #endif