]> git.tdb.fi Git - libs/core.git/blob - source/io/unix/file.cpp
6092cb740172365d878be540121abf565582a949
[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         if(!(mode&M_INHERIT))
39                 flags |= O_CLOEXEC;
40
41         *handle = ::open(fn.c_str(), flags, 0666);
42         if(!handle)
43         {
44                 int err = errno;
45                 if(err==ENOENT)
46                         throw file_not_found(fn);
47                 else if(err==EEXIST)
48                         throw file_already_exists(fn);
49                 else
50                         throw system_error(format("open(%s)", fn), err);
51         }
52 }
53
54 void File::sync()
55 {
56         signal_flush_required.emit();
57
58         fsync(*handle);
59 }
60
61 } // namespace IO
62 } // namespace Msp