]> git.tdb.fi Git - libs/core.git/blob - source/io/file.h
d59cd577fc0f33e1acbcbb62bcaa9fa0bb31c141
[libs/core.git] / source / io / file.h
1 #ifndef MSP_IO_FILE_H_
2 #define MSP_IO_FILE_H_
3
4 #include <stdexcept>
5 #include <string>
6 #include "buffered.h"
7 #include "filtered.h"
8 #include "seekable.h"
9
10 namespace Msp {
11 namespace IO {
12
13 class file_not_found: public std::runtime_error
14 {
15 public:
16         file_not_found(const std::string &fn): std::runtime_error(fn) { }
17 };
18
19
20 /**
21 A class for reading and writing files.
22
23 Non-blocking mode is not supported on Win32.
24 */
25 class File: public Seekable
26 {
27 public:
28         enum CreateMode
29         {
30                 C_NONE = 0,
31                 C_CREATE = 1,
32                 C_TRUNCATE = 2
33         };
34
35 private:
36         Handle handle;
37
38 public:
39         /** Creates a new file object and opens it.  If the create flag is set and
40         write access is requested and the file does exist, it is created.  Otherwise
41         a missing file is an error. */
42         File(const std::string &, Mode = M_READ, CreateMode = CreateMode(C_CREATE+C_TRUNCATE));
43         virtual ~File();
44
45         /** Closes the file.  Any attempt to access the file after this will cause
46         an exception to be thrown. */
47         void close();
48
49         void set_block(bool);
50
51 protected:
52         virtual unsigned do_write(const char *, unsigned);
53         virtual unsigned do_read(char *, unsigned);
54
55 public:
56         virtual void sync();
57
58         virtual unsigned seek(int, SeekType);
59         virtual unsigned tell() const;
60
61         virtual Handle get_event_handle() { return handle; }
62
63 private:
64         void check_access(Mode) const;
65 };
66
67 inline File::CreateMode operator|(File::CreateMode m, File::CreateMode n)
68 { return File::CreateMode(static_cast<int>(m)|static_cast<int>(n)); }
69
70 inline File::CreateMode operator&(File::CreateMode m, File::CreateMode n)
71 { return File::CreateMode(static_cast<int>(m)&static_cast<int>(n)); }
72
73 inline File::CreateMode operator~(File::CreateMode m)
74 { return File::CreateMode(~static_cast<int>(m)); }
75
76 typedef Filtered<File, Buffered> BufferedFile;
77
78 } // namespace IO
79 } // namespace Msp
80
81 #endif