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). */
| 452 | * If you need to close the file early, use file.fclose() instead of fclose(file). |
| 453 | */ |
| 454 | class CAutoFile |
| 455 | { |
| 456 | private: |
| 457 | const int nType; |
| 458 | const int nVersion; |
| 459 | |
| 460 | FILE* file; |
| 461 | |
| 462 | public: |
| 463 | CAutoFile(FILE* filenew, int nTypeIn, int nVersionIn) : nType(nTypeIn), nVersion(nVersionIn) |
| 464 | { |
| 465 | file = filenew; |
| 466 | } |
| 467 | |
| 468 | ~CAutoFile() |
| 469 | { |
| 470 | fclose(); |
| 471 | } |
| 472 | |
| 473 | // Disallow copies |
| 474 | CAutoFile(const CAutoFile&) = delete; |
| 475 | CAutoFile& operator=(const CAutoFile&) = delete; |
| 476 | |
| 477 | void fclose() |
| 478 | { |
| 479 | if (file) { |
| 480 | ::fclose(file); |
| 481 | file = nullptr; |
| 482 | } |
| 483 | } |
| 484 | |
| 485 | /** Get wrapped FILE* with transfer of ownership. |
| 486 | * @note This will invalidate the CAutoFile object, and makes it the responsibility of the caller |
| 487 | * of this function to clean up the returned FILE*. |
| 488 | */ |
| 489 | FILE* release() { FILE* ret = file; file = nullptr; return ret; } |
| 490 | |
| 491 | /** Get wrapped FILE* without transfer of ownership. |
| 492 | * @note Ownership of the FILE* will remain with this class. Use this only if the scope of the |
| 493 | * CAutoFile outlives use of the passed pointer. |
| 494 | */ |
| 495 | FILE* Get() const { return file; } |
| 496 | |
| 497 | /** Return true if the wrapped FILE* is nullptr, false otherwise. |
| 498 | */ |
| 499 | bool IsNull() const { return (file == nullptr); } |
| 500 | |
| 501 | // |
| 502 | // Stream subset |
| 503 | // |
| 504 | int GetType() const { return nType; } |
| 505 | int GetVersion() const { return nVersion; } |
| 506 | |
| 507 | void read(char* pch, size_t nSize) |
| 508 | { |
| 509 | if (!file) |
| 510 | throw std::ios_base::failure("CAutoFile::read: file handle is nullptr"); |
| 511 | if (fread(pch, 1, nSize, file) != nSize) |
no test coverage detected