6 #include <msp/strings/format.h>
7 #include <msp/core/systemerror.h>
9 #include "handle_private.h"
16 File::File(const string &fn, Mode m, CreateMode cm)
19 throw invalid_argument("File::File mode");
20 if(cm&~(C_CREATE|C_TRUNCATE|C_EXCLUSIVE))
21 throw invalid_argument("File::File create");
22 if((cm&C_EXCLUSIVE) && (!(cm&C_CREATE) || (cm&C_TRUNCATE)))
23 throw invalid_argument("File::File create");
30 int create_flags = OPEN_EXISTING;
33 flags |= GENERIC_READ;
37 flags |= GENERIC_WRITE;
39 switch(static_cast<int>(cm))
41 case C_NONE: create_flags = OPEN_EXISTING; break;
42 case C_CREATE: create_flags = OPEN_ALWAYS; break;
43 case C_TRUNCATE: create_flags = TRUNCATE_EXISTING; break;
44 case C_OVERWRITE: create_flags = CREATE_ALWAYS; break;
45 case C_NEW: create_flags = CREATE_NEW; break;
49 share_flags = FILE_SHARE_READ;
51 *handle = CreateFile(fn.c_str(), flags, share_flags, 0, create_flags, FILE_ATTRIBUTE_NORMAL, 0);
54 int err = GetLastError();
55 if(err==ERROR_FILE_NOT_FOUND)
56 throw file_not_found(fn);
57 else if(err==ERROR_FILE_EXISTS)
58 throw file_already_exists(fn);
60 throw system_error(format("CreateFile(%s)", fn), err);
66 case M_READ: flags |= O_RDONLY; break;
67 case M_WRITE: flags |= O_WRONLY; break;
68 case M_RDWR: flags |= O_RDWR; break;
86 *handle = ::open(fn.c_str(), flags, 0666);
91 throw file_not_found(fn);
93 throw file_already_exists(fn);
95 throw system_error(format("open(%s)", fn), err);
102 signal_flush_required.emit();
106 void File::set_block(bool b)
108 mode = (mode&~M_NONBLOCK);
110 mode = (mode|M_NONBLOCK);
112 int flags = fcntl(*handle, F_GETFD);
113 fcntl(*handle, F_SETFL, (flags&O_NONBLOCK)|(b?0:O_NONBLOCK));
117 unsigned File::do_write(const char *buf, unsigned size)
119 check_access(M_WRITE);
129 return sys_write(handle, buf, size);
132 unsigned File::do_read(char *buf, unsigned size)
134 check_access(M_READ);
139 unsigned ret = sys_read(handle, buf, size);
149 signal_flush_required.emit();
155 SeekOffset File::seek(SeekOffset off, SeekType type)
157 signal_flush_required.emit();
158 off = sys_seek(handle, off, type);
164 SeekOffset File::tell() const
166 return sys_seek(const_cast<Handle &>(handle), 0, S_CUR);
169 const Handle &File::get_handle(Mode m)