From 4fa7b1eb606ecd749409a907ea7a47b39d48cb7b Mon Sep 17 00:00:00 2001 From: Jay Berkenbilt Date: Sat, 31 Aug 2019 11:00:53 -0400 Subject: Add remove_file and rename_file to QUtil --- libqpdf/QUtil.cc | 54 +++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 49 insertions(+), 5 deletions(-) (limited to 'libqpdf') diff --git a/libqpdf/QUtil.cc b/libqpdf/QUtil.cc index a3bf1744..db52bdb3 100644 --- a/libqpdf/QUtil.cc +++ b/libqpdf/QUtil.cc @@ -394,15 +394,14 @@ QUtil::os_wrapper(std::string const& description, int status) return status; } -FILE* -QUtil::safe_fopen(char const* filename, char const* mode) -{ - FILE* f = 0; #ifdef _WIN32 +static PointerHolder +win_convert_filename(char const* filename) +{ // Convert the utf-8 encoded filename argument to wchar_t*. First, // convert to utf16, then to wchar_t*. Note that u16 will start // with the UTF16 marker, which we skip. - std::string u16 = utf8_to_utf16(filename); + std::string u16 = QUtil::utf8_to_utf16(filename); size_t len = u16.length(); size_t wlen = (len / 2) - 1; PointerHolder wfilenamep(true, new wchar_t[wlen + 1]); @@ -415,6 +414,17 @@ QUtil::safe_fopen(char const* filename, char const* mode) (static_cast(u16.at(i)) << 8) + static_cast(u16.at(i+1))); } + return wfilenamep; +} +#endif + +FILE* +QUtil::safe_fopen(char const* filename, char const* mode) +{ + FILE* f = 0; +#ifdef _WIN32 + PointerHolder wfilenamep = win_convert_filename(filename); + wchar_t* wfilename = wfilenamep.getPointer(); PointerHolder wmodep(true, new wchar_t[strlen(mode) + 1]); wchar_t* wmode = wmodep.getPointer(); wmode[strlen(mode)] = 0; @@ -537,6 +547,40 @@ QUtil::same_file(char const* name1, char const* name2) return false; } + +void +QUtil::remove_file(char const* path) +{ +#ifdef _WIN32 + PointerHolder wpath = win_convert_filename(path); + os_wrapper(std::string("remove ") + path, _wunlink(wpath.getPointer())); +#else + os_wrapper(std::string("remove ") + path, unlink(path)); +#endif +} + +void +QUtil::rename_file(char const* oldname, char const* newname) +{ +#ifdef _WIN32 + try + { + remove_file(newname); + } + catch (QPDFSystemError&) + { + // ignore + } + PointerHolder wold = win_convert_filename(oldname); + PointerHolder wnew = win_convert_filename(newname); + os_wrapper(std::string("rename ") + oldname + " " + newname, + _wrename(wold.getPointer(), wnew.getPointer())); +#else + os_wrapper(std::string("rename ") + oldname + " " + newname, + rename(oldname, newname)); +#endif +} + char* QUtil::copy_string(std::string const& str) { -- cgit v1.2.3-70-g09d2