判断文件类型,一般情况下可以根据文件后缀约定,使用相应的处理方式处理。
或者基于文件magic number(文件的前512个bytes)对文件类型进行判断,C/C++可以通过libmagic处理判断文件类型,下面是stackoverflow上使用libmagic的实现::
#include <boost/filesystem.hpp>
#include <boost/range.hpp>
#include <iostream>
#include <magic.h>
using namespace boost;
namespace fs = filesystem;
int main() {
auto handle = ::magic_open(MAGIC_NONE|MAGIC_COMPRESS);
::magic_load(handle, NULL);
for (fs::directory_entry const& x : make_iterator_range(fs::directory_iterator("."), {})) {
auto type = ::magic_file(handle, x.path().native().c_str());
std::cout << x.path() << "\t" << (type? type : "UNKOWN") << "\n";
}
::magic_close(handle);
}
输出结果: