COOPY » Guide
version 0.6.5
|
00001 00002 #include <coopy/FileIO.h> 00003 00004 #include <string.h> 00005 00006 using namespace coopy::store; 00007 using namespace std; 00008 00009 bool FileIO::openForWrite(const char *dest, const Property& config) { 00010 if (strcmp(dest,"-")==0) { 00011 fp = stdout; 00012 need_close = false; 00013 } else { 00014 fp = fopen(dest,"wb"); 00015 if (fp!=NULL) { 00016 need_close = true; 00017 } 00018 } 00019 return fp!=NULL; 00020 } 00021 00022 bool FileIO::open(const char *src, const Property& config) { 00023 //printf("OPEN with %s\n", config.toString().c_str()); 00024 if (strcmp(src,"-")==0) { 00025 fp = stdin; 00026 need_close = false; 00027 } else { 00028 fp = fopen(src,"rb"); 00029 if (fp!=NULL) { 00030 need_close = true; 00031 } 00032 } 00033 if (fp!=NULL) { 00034 if (config.get("length").asString()=="header") { 00035 char buf[100] = "x"; 00036 while (buf[0]!=':') { 00037 size_t r = fread(&buf[0],1,1); 00038 if (r==0) break; 00039 } 00040 while (buf[0]!=' ') { 00041 size_t r = fread(&buf[0],1,1); 00042 if (r==0) break; 00043 } 00044 int at = 0; 00045 char ch = 'x'; 00046 do { 00047 size_t r = fread(&buf[at],1,1); 00048 if (r==0) break; 00049 ch = buf[at]; 00050 at++; 00051 } while (ch>='0'&&ch<='9'&&at<=10); 00052 buf[at] = '\0'; 00053 at = atoi(buf); 00054 dbg_printf("Got length %d\n", at); 00055 { 00056 size_t r = fread(&buf[0],1,1); 00057 if (buf[0]!=ch) { 00058 r = fread(&buf[0],2,2); 00059 } 00060 } 00061 00062 has_length = true; 00063 pending_length = at; 00064 } 00065 } 00066 00067 return fp!=NULL; 00068 } 00069 00070 bool FileIO::close() { 00071 if (need_close) { 00072 fclose(fp); 00073 need_close = false; 00074 } 00075 fp = NULL; 00076 return true; 00077 } 00078 00079 00080 size_t FileIO::fread(void *ptr, size_t size, size_t nmemb) { 00081 if (fp==NULL) return 0; 00082 if (!has_length) { 00083 return ::fread(ptr,size,nmemb,fp); 00084 } 00085 if (pending_length==0) return 0; 00086 size_t top = size*nmemb; 00087 if (pending_length<top) top = pending_length; 00088 size_t r = ::fread(ptr,1,top,fp); 00089 if (r == 0) { 00090 pending_length = 0; 00091 } 00092 pending_length -= r; 00093 return r; 00094 } 00095 00096 00097 bool FileIO::openAndWrite(const std::string& txt, const Property& config) { 00098 string name = config.get("file").asString(); 00099 if (name=="-") { 00100 fp = stdout; 00101 need_close = false; 00102 } else { 00103 fp = fopen(name.c_str(),"wb"); 00104 if (!fp) return false; 00105 need_close = true; 00106 } 00107 if (fp!=NULL) { 00108 fwrite(txt.c_str(),1,txt.length(),fp); 00109 } 00110 if (need_close) { 00111 fclose(fp); 00112 } 00113 fp = NULL; 00114 need_close = false; 00115 00116 return true; 00117 }