In my C++ program, I have the string
string s = "/usr/file.gz";
Here, how to make the script to check for .gz extention (whatever the file name is) and split it like "/usr/file"?
In my C++ program, I have the string
string s = "/usr/file.gz";
Here, how to make the script to check for .gz extention (whatever the file name is) and split it like "/usr/file"?
How about:
// Check if the last three characters match the ext.
const std::string ext(".gz");
if ( s != ext &&
s.size() > ext.size() &&
s.substr(s.size() - ext.size()) == ".gz" )
{
// if so then strip them off
s = s.substr(0, s.size() - ext.size());
}
s.size() > 3, as ".gz" is a hidden file and should not be stripped to "". ( * I stripped too much, added * and then did a rm -rf /* )ends_with method like in Java or Python? And what is the point of s != ext? The code would work equally well without that comparison.If you're able to use C++11, you can use #include <regex> or if you're stuck with C++03 you can use Boost.Regex (or PCRE) to form a proper regular expression to break out the parts of a filename you want. Another approach is to use Boost.Filesystem for parsing paths properly.
Since C++17, you can use the built-in filesystem library to treat file paths, which is derived from the BOOST filesystem library. Note that the operator / has been overloaded to concatenate std::filesystem::paths.
#include <filesystem>
std::string stripExtension(const std::string &path_str) {
std::filesystem::path p{path_str};
if (p.extension() == ".gz") {
return p.parent_path() / p.stem();
}
return {};
}
Or shorter version of another answer (C++11)
std::string stripExtension(const std::string &filePath) {
return {filePath, 0, filePath.rfind('.')};
}