MCPcopy Create free account
hub / github.com/ElementsProject/elements / CAutoFile

Class CAutoFile

src/streams.h:475–578  ·  view source on GitHub ↗

Non-refcounted RAII wrapper for FILE* * * Will automatically close the file when it goes out of scope if not null. * If you're returning the file pointer, return file.release(). * If you need to close the file early, use file.fclose() instead of fclose(file). */

Source from the content-addressed store, hash-verified

473 * If you need to close the file early, use file.fclose() instead of fclose(file).
474 */
475class CAutoFile
476{
477private:
478 const int nType;
479 const int nVersion;
480
481 FILE* file;
482
483public:
484 CAutoFile(FILE* filenew, int nTypeIn, int nVersionIn) : nType(nTypeIn), nVersion(nVersionIn)
485 {
486 file = filenew;
487 }
488
489 ~CAutoFile()
490 {
491 fclose();
492 }
493
494 // Disallow copies
495 CAutoFile(const CAutoFile&) = delete;
496 CAutoFile& operator=(const CAutoFile&) = delete;
497
498 void fclose()
499 {
500 if (file) {
501 ::fclose(file);
502 file = nullptr;
503 }
504 }
505
506 /** Get wrapped FILE* with transfer of ownership.
507 * @note This will invalidate the CAutoFile object, and makes it the responsibility of the caller
508 * of this function to clean up the returned FILE*.
509 */
510 FILE* release() { FILE* ret = file; file = nullptr; return ret; }
511
512 /** Get wrapped FILE* without transfer of ownership.
513 * @note Ownership of the FILE* will remain with this class. Use this only if the scope of the
514 * CAutoFile outlives use of the passed pointer.
515 */
516 FILE* Get() const { return file; }
517
518 /** Return true if the wrapped FILE* is nullptr, false otherwise.
519 */
520 bool IsNull() const { return (file == nullptr); }
521
522 //
523 // Stream subset
524 //
525 int GetType() const { return nType; }
526 int GetVersion() const { return nVersion; }
527
528 void read(Span<std::byte> dst)
529 {
530 if (!file)
531 throw std::ios_base::failure("CAutoFile::read: file handle is nullptr");
532 if (fread(dst.data(), 1, dst.size(), file) != dst.size()) {

Callers

nothing calls this directly

Calls 2

UnserializeFunction · 0.85
SerializeFunction · 0.70

Tested by

no test coverage detected