diff --git a/src/file_utils.cpp b/src/file_utils.cpp index 15b30e3b6..8a078fe18 100644 --- a/src/file_utils.cpp +++ b/src/file_utils.cpp @@ -28,11 +28,24 @@ bool file_exists(const std::string& filename) std::string get_file_extension(const std::string& filename) { + // try our best to work on windows... +#if defined(_WIN32) || defined(_WIN64) + const char sep_char = '\\'; +#else + const char sep_char = '/'; +#endif + // check that at least one letter is present const auto last_period_pos = filename.find_last_of('.'); + const auto last_sep_pos = filename.find_last_of(sep_char); - // no file extension - if (last_period_pos == std::string::npos) + // no file extension. In the first case, we are only given + // a file name. In the second, we have been given a file path. + // If that's the case, periods are allowed in directory names, + // but have the interpretation as preceding a file extension + // after the last separator. + if (last_period_pos == std::string::npos || + (last_sep_pos < std::string::npos && last_period_pos < last_sep_pos)) return ""; const std::string ending = filename.substr(last_period_pos + 1); diff --git a/tests/cpp_unit_tests/test_file_utils.cpp b/tests/cpp_unit_tests/test_file_utils.cpp index 69d9b5a59..3b7a74346 100644 --- a/tests/cpp_unit_tests/test_file_utils.cpp +++ b/tests/cpp_unit_tests/test_file_utils.cpp @@ -12,6 +12,8 @@ TEST_CASE("Test get_file_extension") REQUIRE(get_file_extension("wasssssup_lol") == ""); REQUIRE(get_file_extension("has_directory/secret_file") == ""); REQUIRE(get_file_extension("lovely.dir/extensionless_file") == ""); + REQUIRE(get_file_extension("lovely.dir/statepoint.20.h5") == "h5"); + REQUIRE(get_file_extension("lovely.dir/asdf123.cpp") == "cpp"); } TEST_CASE("Test dir_exists") @@ -25,5 +27,6 @@ TEST_CASE("Test dir_exists") TEST_CASE("Test file_exists") { - // TODO make a file test it exists, delete it + // Note: not clear how to portably test where a file should exist. + REQUIRE(!file_exists("./should_not_exist/really_do_not_make_this_please")); }