00001 #ifndef Impala_Basis_File_h
00002 #define Impala_Basis_File_h
00003
00004 #include <cstdio>
00005 #include <cstring>
00006 #include <iostream>
00007 #include "Basis/String.h"
00008
00009 namespace Impala
00010 {
00011
00012
00016 class File
00017 {
00018 public:
00019
00020 File()
00021 {
00022 mFp = 0;
00023 mBuf = 0;
00024 }
00025
00026 File(CString fileName, String mode, bool printError = true,
00027 int lineBufSize = 100000)
00028 {
00029 mBuf = 0;
00030 if (!(mFp=fopen(fileName.c_str(), mode.c_str())))
00031 {
00032 if (printError)
00033 std::cout << "Error opening (mode = " << mode << ") file "
00034 << fileName << std::endl;
00035 return;
00036 }
00037 mBufSize = lineBufSize;
00038 mBuf = new char[mBufSize];
00039 }
00040
00041 ~File()
00042 {
00043 Close();
00044 if (mBuf)
00045 delete mBuf;
00046 }
00047
00048 bool
00049 Valid() const
00050 {
00051 return mFp != 0;
00052 }
00053
00054 void
00055 Close()
00056 {
00057 if (mFp)
00058 {
00059 fclose(mFp);
00060 mFp = 0;
00061 }
00062 }
00063
00064 bool
00065 Eof()
00066 {
00067 return feof(mFp) ? true : false;
00068 }
00069
00070
00071
00072 String
00073 ReadLine(bool skipEC = false)
00074 {
00075 mBuf[0] = '\0';
00076 bool found = (skipEC) ? false : true;
00077 do
00078 {
00079 fgets(mBuf, mBufSize, mFp);
00080 if (strlen(mBuf) > 0 && mBuf[0] != '#' && mBuf[0] != '\r')
00081 found = true;
00082 if (!found && feof(mFp))
00083 {
00084 mBuf[0] = '\0';
00085 found = true;
00086 }
00087 }
00088 while (! found);
00089
00090 int len = strlen(mBuf);
00091 if (len == 0)
00092 return String("");
00093 while ((mBuf[len-1] == '\n') || (mBuf[len-1] == '\r'))
00094 {
00095 mBuf[len-1] = '\0';
00096 len = len - 1;
00097 }
00098 return String(mBuf, len);
00099 }
00100
00101 FILE*
00102 Fp()
00103 {
00104 return mFp;
00105 }
00106
00107 void
00108 Rewind()
00109 {
00110 if (mFp)
00111 {
00112 if (fseek(mFp, 0, SEEK_SET) != 0)
00113 std::cout << "[File::Rewind] error" << std::endl;
00114 }
00115 }
00116
00117 int
00118 Size()
00119 {
00120 int pos = ftell(mFp);
00121 fseek(mFp, 0, SEEK_END);
00122 int size = ftell(mFp);
00123 fseek(mFp, 0, pos);
00124 return size;
00125 }
00126
00127 int
00128 GetPosition()
00129 {
00130 return ftell(mFp);
00131 }
00132
00133 private:
00134
00135
00136 File(const File& f)
00137 {
00138 }
00139
00140 File&
00141 operator=(const File& f)
00142 {
00143 return *this;
00144 }
00145
00146 FILE* mFp;
00147 char* mBuf;
00148 int mBufSize;
00149 };
00150
00151 }
00152
00153 #endif