C ++:如何检查文件的类型,而扩展 [英] C++: How to check type of files without extension
问题描述
我使用boost ::文件系统中的目录搜索和处理文件。
但是,而不是处理的每一个文件我想只处理的文本文件(通过使用boost ::文件系统:: is_regular_file()检查)(或至少忽略二进制文件)。
I am using boost::filesystem to search and process files in a directory. But instead of processing every file (checked by using boost::filesystem::is_regular_file()) I want to only process text files (or at least ignore binary files).
有没有一种方法,我怎么能做到这一点,即使文件的不具有扩展
Is there a way how I can achieve that even if files do not have an extension?
我会强烈AP preciate一个独立于平台的解决方案。
I would highly appreciate a platform independent solution.
推荐答案
使用 libmagic
Libmagic可在所有主要平台(和许多未成年人)。
Libmagic is available on all major platforms (and many minors).
#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);
}
打印,例如
sehe@desktop:~/custom/boost/status$ /tmp/test
"./Jamfile.v2" ASCII text
"./explicit-failures.xsd" XML document text
"./expected_results.xml" XML document text
"./explicit-failures-markup.xml" XML document text
您可以使用该标志来控制分类的细节,例如MAGIC_MIME:
You can use the flags to control the detail of classification, e.g. MAGIC_MIME:
sehe@desktop:~/custom/boost/status$ /tmp/test
"./Jamfile.v2" text/plain; charset=us-ascii
"./explicit-failures.xsd" application/xml; charset=us-ascii
"./expected_results.xml" application/xml; charset=us-ascii
"./explicit-failures-markup.xml" application/xml; charset=utf-8
或加载刚的/ etc /魔术
:
sehe@desktop:~/custom/boost/status$ /tmp/test
"./Jamfile.v2" ASCII text
"./explicit-failures.xsd" ASCII text
"./expected_results.xml" ASCII text, with very long lines
"./explicit-failures-markup.xml" UTF-8 Unicode text
这篇关于C ++:如何检查文件的类型,而扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!