This problem is quite "a classic", but I can't find a good solution to it.
I am using CreateFile
to open a file. Sometimes I would want it to be read-only, sometimes write-only and sometimes I would want the same file to support both read and write. Of course I would like to follow RAII principles.
I am trying to accomplish multiple goals and not so sure how:
If a file was opened only for reading, I don't want it to be possible to write to it (which will result in a runtime error/undefined behaviour). In other words, if
file1
was opened with read-only permissions I wantfile1.write_to_file()
to not even compile. What that means is that I can't have one largeFile
class with both read and write operations.I don't want to expose the handle that is returned in
CreateFile
. The handle absolutely cannot be apublic
field nor can it be returned from apublic
getter in the class where it will be stored.
I think it is pretty evident that a basic File
class will be necessary. File
will call CreateFile
and hold the handle returned from it. How should I proceed from there?
If I define
ReadFile
andWriteFile
that inherit fromFile
, how would I defineReadWriteFile
? I would like to avoid multiple inheritance and virtual inheritance.If I try to go for composition (making
File
a field ofReadFile
), how willReadFile
get the handle to the file fromFile
?A third way is to not define
File
. OnlyReadFile
,WriteFile
andReadWriteFile
, however that introduces some code duplication because the constructor and destructor ofReadFile
andWriteFile
would be very similar.
Please do not offer to use fstream
or other methods that do not rely on WinAPI.