Move most platform-specific code into overlay directories
[libs/core.git] / source / io / unix / file.cpp
1 #include <errno.h>
2 #include <fcntl.h>
3 #include <unistd.h>
4 #include <msp/core/systemerror.h>
5 #include <msp/strings/format.h>
6 #include "file.h"
7 #include "handle_private.h"
8
9 using namespace std;
10
11 namespace Msp {
12 namespace IO {
13
14 void File::platform_init(const string &fn, CreateMode cm)
15 {
16         int flags = 0;
17         switch(mode&M_RDWR)
18         {
19         case M_READ:  flags |= O_RDONLY; break;
20         case M_WRITE: flags |= O_WRONLY; break;
21         case M_RDWR:  flags |= O_RDWR; break;
22         default:;
23         }
24
25         if(mode&M_WRITE)
26         {
27                 if(cm&C_CREATE)
28                         flags |= O_CREAT;
29                 if(cm&C_TRUNCATE)
30                         flags |= O_TRUNC;
31                 if(cm&C_EXCLUSIVE)
32                         flags |= O_EXCL;
33         }
34         if(mode&M_APPEND)
35                 flags |= O_APPEND;
36         if(mode&M_NONBLOCK)
37                 flags |= O_NONBLOCK;
38
39         *handle = ::open(fn.c_str(), flags, 0666);
40         if(!handle)
41         {
42                 int err = errno;
43                 if(err==ENOENT)
44                         throw file_not_found(fn);
45                 else if(err==EEXIST)
46                         throw file_already_exists(fn);
47                 else
48                         throw system_error(format("open(%s)", fn), err);
49         }
50 }
51
52 void File::sync()
53 {
54         signal_flush_required.emit();
55
56         fsync(*handle);
57 }
58
59 } // namespace IO
60 } // namespace Msp