c++ - Creating a new file avoiding race conditions -
i need develop c++ routine performing apparently trivial task: create file if not exist, else nothing/raise error.
as need avoid race conditions, want use "ask forgiveness not permission" principle (i.e. attempting intended operation , checking if succeeded, opposed checking preconditions in advance), which, knowledge, robust , portable method purpose [wikipedia article][an example getline].
still, not find way implement in case. best come opening fstream
in app
mode (or fopen
ing "a"
), checking output position tellp
(c++) or ftell
(c) , aborting if such position not zero. has 2 disadvantages, namely if file exists gets locked (although short time) , modification date altered.
i checked other possible combinations of ios_base::openmode
fstream
, mode
strings of fopen
found no option suited needs. further search in c , c++ standard libraries, boost filesystem, proved unfruitful.
can point out method perform task in robust way (no collateral effects, no race conditions) without relying on os-specific functions? specific problem in windows, portable solutions preferred.
edit: answer bitwhistler solves problem c programs. still, amazed no c++ idiomatic solution seems exist. either 1 uses open
o_excl
attribute proposed andrew henle, os-specific (in windows attribute seems called _o_excl
additional underscore [msdn]) or 1 separately compiles c11 file , links c++ code. moreover, file descriptor obtained cannot converted stream except nonstandard extensions (e.g. gcc's __gnu_cxx::stdio_filebuf
). hope future version of c++ implement "x"
subattribute , possibly corresponding ios::
modificator file streams.
the new c standard (c2011, not part of c++) adds new standard subspecifier ("x"), can appended "w" specifier (to form "wx", "wbx", "w+x" or "w+bx"/"wb+x"). subspecifier forces function fail if file exists, instead of overwriting it.
Comments
Post a Comment