00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020 #include "File.h"
00021 #include "File.h"
00022
00023 #include <strstream>
00024
00025 #include <unistd.h>
00026 #include <fcntl.h>
00027 #include <errno.h>
00028
00034 void utils::File::write(const string &s, const string &name, const string &dir, bool always=false)
00035 throw(MEMError, IOError, AlreadyPresent) {
00036 string fullname = name;
00037 if(dir.length() != 0)
00038 fullname = dir + "/" + fullname;
00039
00040 int fd;
00041 if(always)
00042 fd = open(fullname.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0664);
00043 else
00044 fd = open(fullname.c_str(), O_CREAT | O_EXCL | O_WRONLY, 0664);
00045
00046 if(fd < 0)
00047 switch(errno) {
00048 case EEXIST:
00049 throw AlreadyPresent();
00050 default:
00051 throw IOError();
00052 };
00053 int nbytes;
00054
00055 const char * cs = s.c_str();
00056 size_t len = s.length();
00057
00058 do {
00059 nbytes = ::write(fd, cs, len);
00060 } while (nbytes == -1 && errno == EINTR);
00061
00062 close(fd);
00063 if(nbytes < 0) {
00064 unlink(name.c_str());
00065 throw IOError();
00066 }
00067 };
00068
00069 string utils::File::read(const string &name, const string &dir) throw(MEMError, IOError, NotFound) {
00070 string fullname = name;
00071 if(dir.length() != 0)
00072 fullname = dir + "/" + fullname;
00073
00074 int fd = open(fullname.c_str(), 0);
00075 if(fd < 0)
00076 switch(errno) {
00077 case ENOENT:
00078 throw NotFound();
00079 default:
00080 throw IOError();
00081 };
00082
00083 string s;
00084 char c;
00085 int k=0;
00086 while(-1) {
00087 int i = ::read(fd, &c, 1);
00088 if(i==0)
00089 break;
00090 if(i == -1 && errno == EINTR)
00091 continue;
00092 if(i<0) {
00093 close(fd);
00094 throw IOError();
00095 };
00096 s += c;
00097 };
00098 close(fd);
00099 return s;
00100 };
00101
00102 void utils::File::remove(const string &name, const string &dir) throw(IOError, NotFound) {
00103 string fullname = name;
00104 if(dir.length() != 0)
00105 fullname = dir + "/" + fullname;
00106
00107 int res = unlink(fullname.c_str());
00108 if(res == 0)
00109 return;
00110 switch(errno) {
00111 case ENOENT:
00112 throw NotFound();
00113 default:
00114 throw IOError();
00115 };
00116 };