00001 #ifndef moses_DynSAInclude_file_h 00002 #define moses_DynSAInclude_file_h 00003 00004 #include <iostream> 00005 #include <fstream> 00006 #include <cstdio> 00007 #include <cstdlib> 00008 #include <sys/stat.h> 00009 #include <string> 00010 #include "util/check.hh" 00011 #include "fdstream.h" 00012 #include "utils.h" 00013 00014 namespace Moses 00015 { 00016 typedef std::string FileExtension; 00017 00019 class FileHandler: public std::fstream 00020 { 00021 public: 00022 // descriptors for stdin and stdout 00023 static const std::string kStdInDescriptor; // file name for std::cin 00024 static const std::string kStdOutDescriptor; // file name for std::cout 00025 // compression commands 00026 static const std::string kCatCommand; // i.e. no compression 00027 static const std::string kGzipCommand; // gzip -f 00028 static const std::string kGunzipCommand; // gunzip -f 00029 static const std::string kBzip2Command; // bzip2 -f 00030 static const std::string kBunzip2Command; // bunzip2 -f 00031 00032 // open file or wrap stdin or stdout 00033 FileHandler(const std::string & path, 00034 std::ios_base::openmode flags = std::ios::in, 00035 bool checkExists = true); 00036 ~FileHandler(); 00037 // file utilities 00038 static bool getCompressionCmds(const std::string & filepath, 00039 std::string & compressionCmd, 00040 std::string & decompressionCmd, 00041 std::string & compressionSuffix); 00042 00043 // data accessors 00044 std::string getPath() { 00045 return path_; 00046 } 00047 std::ios_base::openmode getFlags() { 00048 return flags_; 00049 } 00050 bool isStdIn() { 00051 return path_ == FileHandler::kStdInDescriptor; 00052 } 00053 bool isStdOut() { 00054 return path_ == FileHandler::kStdOutDescriptor; 00055 } 00056 bool reset(); 00057 protected: 00058 static const FileExtension kGzipped; 00059 static const FileExtension kBzipped2; 00060 bool fileExists(); 00061 bool setStreamBuffer(bool checkExists); 00062 bool isCompressedFile(std::string & cmd); 00063 fdstreambuf* openCompressedFile(const char* cmd); 00064 std::string path_; // file path 00065 std::ios_base::openmode flags_; // open flags 00066 std::streambuf* buffer_; // buffer to either gzipped or standard data 00067 std::FILE* fp_; //file pointer to handle pipe data 00068 }; 00069 00070 } // end namespace 00071 00072 #endif