file.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. /////////////////////////////////////////////////////////////////////////////
  2. // Name: file.h
  3. // Purpose: interface of wxTempFile, wxFile
  4. // Author: wxWidgets team
  5. // Licence: wxWindows licence
  6. /////////////////////////////////////////////////////////////////////////////
  7. /**
  8. @class wxTempFile
  9. wxTempFile provides a relatively safe way to replace the contents of the
  10. existing file. The name is explained by the fact that it may be also used as
  11. just a temporary file if you don't replace the old file contents.
  12. Usually, when a program replaces the contents of some file it first opens it for
  13. writing, thus losing all of the old data and then starts recreating it.
  14. This approach is not very safe because during the regeneration of the file bad
  15. things may happen: the program may find that there is an internal error preventing
  16. it from completing file generation, the user may interrupt it (especially if file
  17. generation takes long time) and, finally, any other external interrupts (power
  18. supply failure or a disk error) will leave you without either the original file
  19. or the new one.
  20. wxTempFile addresses this problem by creating a temporary file which is meant to
  21. replace the original file - but only after it is fully written. So, if the user
  22. interrupts the program during the file generation, the old file won't be lost.
  23. Also, if the program discovers itself that it doesn't want to replace the old
  24. file there is no problem - in fact, wxTempFile will @b not replace the old
  25. file by default, you should explicitly call wxTempFile::Commit() to do it.
  26. Calling wxTempFile::Discard() explicitly discards any modifications: it
  27. closes and deletes the temporary file and leaves the original file unchanged.
  28. If you call neither Commit() nor Discard(), the destructor will
  29. call Discard() automatically.
  30. To summarize: if you want to replace another file, create an instance of
  31. wxTempFile passing the name of the file to be replaced to the constructor.
  32. (You may also use default constructor and pass the file name to wxTempFile::Open.)
  33. Then you can write to wxTempFile using wxFile-like functions and later call
  34. wxTempFile::Commit() to replace the old file (and close this one) or call
  35. wxTempFile::Discard() to cancel the modifications.
  36. @library{wxbase}
  37. @category{file}
  38. */
  39. class wxTempFile
  40. {
  41. public:
  42. /**
  43. Associates wxTempFile with the file to be replaced and opens it.
  44. @warning
  45. You should use IsOpened() to verify that the constructor succeeded.
  46. */
  47. wxTempFile(const wxString& strName);
  48. /**
  49. Destructor calls Discard() if temporary file is still open.
  50. */
  51. ~wxTempFile();
  52. /**
  53. Validate changes: deletes the old file of name m_strName and renames the new
  54. file to the old name. Returns @true if both actions succeeded.
  55. If @false is returned it may unfortunately mean two quite different things:
  56. either that the old file couldn't be deleted or that the new file
  57. couldn't be renamed to the old name.
  58. */
  59. bool Commit();
  60. /**
  61. Discard changes: the old file contents are not changed, the temporary
  62. file is deleted.
  63. */
  64. void Discard();
  65. /**
  66. Flush the data written to the file to disk.
  67. This simply calls wxFile::Flush() for the underlying file and may be
  68. necessary with file systems such as XFS and Ext4 under Linux. Calling
  69. this function may however have serious performance implications and
  70. also is not necessary with many other file systems so it is not done by
  71. default -- but you can call it before calling Commit() to absolutely
  72. ensure that the data was indeed written to the disk correctly.
  73. */
  74. bool Flush();
  75. /**
  76. Returns @true if the file was successfully opened.
  77. */
  78. bool IsOpened() const;
  79. /**
  80. Returns the length of the file.
  81. This method may return ::wxInvalidOffset if the length couldn't be
  82. determined or 0 even for non-empty files if the file is not seekable.
  83. In general, the only way to determine if the file for which this function
  84. returns 0 is really empty or not is to try reading from it.
  85. */
  86. wxFileOffset Length() const;
  87. /**
  88. Open the temporary file, returns @true on success, @false if an error
  89. occurred.
  90. @a strName is the name of file to be replaced. The temporary file is always
  91. created in the directory where @a strName is. In particular, if @a strName
  92. doesn't include the path, it is created in the current directory and the
  93. program should have write access to it for the function to succeed.
  94. */
  95. bool Open(const wxString& strName);
  96. /**
  97. Seeks to the specified position.
  98. */
  99. wxFileOffset Seek(wxFileOffset ofs,
  100. wxSeekMode mode = wxFromStart);
  101. /**
  102. Returns the current position or ::wxInvalidOffset if file is not opened or
  103. if another error occurred.
  104. */
  105. wxFileOffset Tell() const;
  106. /**
  107. Write to the file, return @true on success, @false on failure.
  108. The second argument is only meaningful in Unicode build of wxWidgets when
  109. @a conv is used to convert @a str to multibyte representation.
  110. */
  111. bool Write(const wxString& str,
  112. const wxMBConv& conv = wxConvUTF8);
  113. };
  114. /**
  115. @class wxFile
  116. A wxFile performs raw file I/O. This is a very small class designed to
  117. minimize the overhead of using it - in fact, there is hardly any overhead at
  118. all, but using it brings you automatic error checking and hides differences
  119. between platforms and compilers. wxFile also automatically closes the file in
  120. its destructor so you won't forget to do so.
  121. wxFile is a wrapper around @c file descriptor. - see also wxFFile for a
  122. wrapper around @c FILE structure.
  123. ::wxFileOffset is used by the wxFile functions which require offsets as
  124. parameter or return them. If the platform supports it, wxFileOffset is a
  125. typedef for a native 64 bit integer, otherwise a 32 bit integer is used for
  126. ::wxFileOffset.
  127. @library{wxbase}
  128. @category{file}
  129. */
  130. class wxFile
  131. {
  132. public:
  133. /**
  134. The OpenMode enumeration defines the different modes for opening a file with wxFile.
  135. It is also used with wxFile::Access function.
  136. */
  137. enum OpenMode {
  138. /** Open file for reading or test if it can be opened for reading with Access() */
  139. read,
  140. /** Open file for writing deleting the contents of the file if it already exists
  141. or test if it can be opened for writing with Access(). */
  142. write,
  143. /** Open file for reading and writing; cannot be used with Access() */
  144. read_write,
  145. /** Open file for appending: the file is opened for writing, but the old contents
  146. of the file are not erased and the file pointer is initially placed at the end
  147. of the file; cannot be used with Access().
  148. This is the same as OpenMode::write if the file doesn't exist.
  149. */
  150. write_append,
  151. /**
  152. Open the file securely for writing (Uses O_EXCL | O_CREAT).
  153. Will fail if the file already exists, else create and open it atomically.
  154. Useful for opening temporary files without being vulnerable to race exploits.
  155. */
  156. write_excl
  157. };
  158. /**
  159. Standard file descriptors
  160. */
  161. enum { fd_invalid = -1, fd_stdin, fd_stdout, fd_stderr };
  162. /**
  163. Default constructor.
  164. */
  165. wxFile();
  166. /**
  167. Opens a file with a filename.
  168. @param filename
  169. The filename.
  170. @param mode
  171. The mode in which to open the file.
  172. @warning
  173. You should use IsOpened() to verify that the constructor succeeded.
  174. */
  175. wxFile(const wxString& filename,
  176. wxFile::OpenMode mode = wxFile::read);
  177. /**
  178. Associates the file with the given file descriptor, which has already been
  179. opened. See Attach() for the list of predefined descriptors.
  180. @param fd
  181. An existing file descriptor.
  182. */
  183. wxFile(int fd);
  184. /**
  185. Destructor will close the file.
  186. @note This destructor is not virtual so you should not use wxFile polymorphically.
  187. */
  188. ~wxFile();
  189. /**
  190. Returns the error code for the last unsuccessful operation.
  191. The error code is system-dependent and corresponds to the value of the
  192. standard @c errno variable when the last error occurred.
  193. Notice that only simple accessors such as IsOpened() and Eof() (and
  194. this method itself) don't modify the last error value, all other
  195. methods can potentially change it if an error occurs, including the
  196. const ones such as Tell() or Length().
  197. @since 2.9.2
  198. @see ClearLastError()
  199. */
  200. int GetLastError() const;
  201. /**
  202. Resets the error code.
  203. GetLastError() will return 0 until the next error occurs.
  204. @since 2.9.2
  205. */
  206. void ClearLastError();
  207. /**
  208. This function verifies if we may access the given file in specified mode.
  209. Only values of @c wxFile::read or @c wxFile::write really make sense here.
  210. */
  211. static bool Access(const wxString& name, wxFile::OpenMode mode);
  212. /**
  213. Attaches an existing file descriptor to the wxFile object.
  214. Examples of predefined file descriptors are 0, 1 and 2 which correspond to
  215. stdin, stdout and stderr (and have symbolic names of @c wxFile::fd_stdin,
  216. @c wxFile::fd_stdout and @c wxFile::fd_stderr).
  217. The descriptor should be already opened and it will be closed by wxFile
  218. object.
  219. */
  220. void Attach(int fd);
  221. /**
  222. Closes the file.
  223. */
  224. bool Close();
  225. /**
  226. Creates a file for writing.
  227. If the file already exists, setting @b overwrite to @true will ensure
  228. it is overwritten.
  229. @a access may be an OR combination of the ::wxPosixPermissions enumeration
  230. values.
  231. */
  232. bool Create(const wxString& filename,
  233. bool overwrite = false,
  234. int access = wxS_DEFAULT);
  235. /**
  236. Get back a file descriptor from wxFile object - the caller is responsible for
  237. closing the file if this descriptor is opened.
  238. IsOpened() will return @false after call to Detach().
  239. @return The file descriptor (this is new since wxWidgets 3.0.0, in the
  240. previous versions this method didn't return anything).
  241. */
  242. int Detach();
  243. /**
  244. Returns @true if the end of the file has been reached.
  245. Note that the behaviour of the file pointer-based class wxFFile is
  246. different as wxFFile::Eof() will return @true here only if an
  247. attempt has been made to read @b past the last byte of the file, while
  248. wxFile::Eof() will return @true even before such attempt is made if the
  249. file pointer is at the last position in the file.
  250. Note also that this function doesn't work on unseekable file descriptors
  251. (examples include pipes, terminals and sockets under Unix) and an attempt to
  252. use it will result in an error message.
  253. So, to read the entire file into memory, you should write a loop which uses
  254. Read() repeatedly and tests its return condition instead of using Eof()
  255. as this will not work for special files under Unix.
  256. */
  257. bool Eof() const;
  258. /**
  259. Returns @true if the given name specifies an existing regular file
  260. (not a directory or a link).
  261. */
  262. static bool Exists(const wxString& filename);
  263. /**
  264. Flushes the file descriptor.
  265. Note that Flush() is not implemented on some Windows compilers due to a
  266. missing fsync function, which reduces the usefulness of this function
  267. (it can still be called but it will do nothing on unsupported compilers).
  268. */
  269. bool Flush();
  270. /**
  271. Returns the type of the file.
  272. */
  273. wxFileKind GetKind() const;
  274. /**
  275. Returns @true if the file has been opened.
  276. */
  277. bool IsOpened() const;
  278. /**
  279. Returns the length of the file.
  280. */
  281. wxFileOffset Length() const;
  282. /**
  283. Opens the file, returning @true if successful.
  284. @param filename
  285. The filename.
  286. @param mode
  287. The mode in which to open the file.
  288. @param access
  289. An OR-combination of ::wxPosixPermissions enumeration values.
  290. */
  291. bool Open(const wxString& filename, wxFile::OpenMode mode = wxFile::read,
  292. int access = wxS_DEFAULT);
  293. /**
  294. Reads from the file into a memory buffer.
  295. @param buffer
  296. Buffer to write in
  297. @param count
  298. Bytes to read
  299. @return The number of bytes read, or the symbol ::wxInvalidOffset.
  300. */
  301. ssize_t Read(void* buffer, size_t count);
  302. /**
  303. Reads the entire contents of the file into a string.
  304. @param str
  305. Non-@NULL pointer to a string to read data into.
  306. @param conv
  307. Conversion object to use in Unicode build; by default supposes
  308. that file contents is encoded in UTF-8 but falls back to the
  309. current locale encoding (or Latin-1 if it is UTF-8 too) if it is
  310. not.
  311. @return @true if file was read successfully, @false otherwise.
  312. @since 2.9.5
  313. */
  314. bool ReadAll(wxString* str, const wxMBConv& conv = wxConvAuto());
  315. /**
  316. Seeks to the specified position.
  317. @param ofs
  318. Offset to seek to.
  319. @param mode
  320. One of wxFromStart, wxFromEnd, wxFromCurrent.
  321. @return The actual offset position achieved, or ::wxInvalidOffset on
  322. failure.
  323. */
  324. wxFileOffset Seek(wxFileOffset ofs,
  325. wxSeekMode mode = wxFromStart);
  326. /**
  327. Moves the file pointer to the specified number of bytes relative to the
  328. end of the file. For example, @c SeekEnd(-5) would position the pointer 5
  329. bytes before the end.
  330. @param ofs
  331. Number of bytes before the end of the file.
  332. @return The actual offset position achieved, or ::wxInvalidOffset on
  333. failure.
  334. */
  335. wxFileOffset SeekEnd(wxFileOffset ofs = 0);
  336. /**
  337. Returns the current position or ::wxInvalidOffset if file is not opened or
  338. if another error occurred.
  339. */
  340. wxFileOffset Tell() const;
  341. /**
  342. Write data to the file (descriptor).
  343. @param buffer
  344. Buffer from which to read data
  345. @param count
  346. Number of bytes to write
  347. @return The number of bytes written.
  348. */
  349. size_t Write(const void *buffer, size_t count);
  350. /**
  351. Writes the contents of the string to the file, returns @true on success.
  352. The second argument is only meaningful in Unicode build of wxWidgets when
  353. @a conv is used to convert @a s to a multibyte representation.
  354. Note that this method only works with @c NUL-terminated strings, if you want
  355. to write data with embedded @c NULs to the file you should use the other
  356. Write() overload.
  357. */
  358. bool Write(const wxString& s, const wxMBConv& conv = wxConvUTF8);
  359. /**
  360. Returns the file descriptor associated with the file.
  361. */
  362. int fd() const;
  363. };