C++如何精准判断std::filesystem路径对应文件后缀为.png?
问题原因
你的原始代码存在3个核心问题:
- 没有先排除文件夹路径,会把名称后缀带
.png的目录也判定为合法文件 - 直接对全路径字符串做
.png匹配,若上级目录名包含.png会得到错误的匹配位置 - 未判断路径字符串总长度是否≥4,当遇到文件名短于4个字符的路径时,
size()-4会发生无符号整数下溢,得到极大值,导致find结果永远不可能相等,这就是你遇到的「非png文件之后第一个文件始终返回false」的核心诱因。
正确实现
直接用std::filesystem内置的路径属性、后缀提取方法即可,不需要手动做字符串匹配:
#include <filesystem> namespace fs = std::filesystem; // 条件判断写为: if (fs::is_regular_file(fileLocation) && fileLocation.path().extension() == ".png") { // 你的业务逻辑 }
如果需要兼容大写后缀(比如.PNG、.Png这类不标准的命名),可以把后缀转成小写再判断:
#include <algorithm> #include <cctype> #include <filesystem> #include <string> namespace fs = std::filesystem; // 封装字符串转小写工具函数 std::string str_tolower(std::string s) { std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c){ return std::tolower(c); } ); return s; } // 条件判断: if (fs::is_regular_file(fileLocation) && str_tolower(fileLocation.path().extension().string()) == ".png") { // 你的业务逻辑 }
实现说明
fs::is_regular_file直接过滤掉文件夹、符号链接等非普通文件的路径path::extension()会直接提取路径最后一个.之后的部分作为后缀,天然就能规避file.png.mcmeta这类文件(这类文件的extension()返回的是.mcmeta,不是.png)- 完全避免了手动处理字符串匹配、长度计算带来的溢出、误匹配问题
内容的提问来源于stack exchange,提问作者Itay123
相关产品推荐
相关产品推荐

