aboutsummaryrefslogtreecommitdiffstats
path: root/include/qpdf/QUtil.hh
diff options
context:
space:
mode:
authorJay Berkenbilt <ejb@ql.org>2022-05-18 16:45:54 +0200
committerJay Berkenbilt <ejb@ql.org>2022-05-20 15:16:25 +0200
commit23fc6756f1894e1af35853eb2251f08d5b25cf30 (patch)
tree288f098cc0273dc819621ae4f0eb3b5c9f58360b /include/qpdf/QUtil.hh
parent0fe8d4476205c97e402e555aac41a88e70e3e9b2 (diff)
downloadqpdf-23fc6756f1894e1af35853eb2251f08d5b25cf30.tar.zst
Add QUtil::FileCloser to the public API
Diffstat (limited to 'include/qpdf/QUtil.hh')
-rw-r--r--include/qpdf/QUtil.hh27
1 files changed, 27 insertions, 0 deletions
diff --git a/include/qpdf/QUtil.hh b/include/qpdf/QUtil.hh
index 5d33b2a5..283db861 100644
--- a/include/qpdf/QUtil.hh
+++ b/include/qpdf/QUtil.hh
@@ -114,6 +114,33 @@ namespace QUtil
QPDF_DLL
FILE* fopen_wrapper(std::string const&, FILE*);
+ // This is a little class to help with automatic closing files.
+ // You can do something like
+ //
+ // QUtil::FileCloser fc(QUtil::safe_fopen(filename, "rb"));
+ //
+ // and then use fc.f to the file. Be sure to actually declare a
+ // variable of type FileCloser. Using it as a temporary won't work
+ // because it will close the file as soon as it goes out of scope.
+ class FileCloser
+ {
+ public:
+ FileCloser(FILE* f) :
+ f(f)
+ {
+ }
+
+ ~FileCloser()
+ {
+ if (f) {
+ fclose(f);
+ f = nullptr;
+ }
+ }
+
+ FILE* f;
+ };
+
// Attempt to open the file read only and then close again
QPDF_DLL
bool file_can_be_opened(char const* filename);