最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c++ - Get the file type shown in File Explorer - Stack Overflow

programmeradmin0浏览0评论

File Explorer has a Type column that indicates the file type. For example, for a file with the extension .txt, the Type column contains Text Document, and for a file with the extension .jpg, this column contains JPG File, and so on.

Is it possible to programmatically get the value from the Type column for a given file using C++?

File Explorer has a Type column that indicates the file type. For example, for a file with the extension .txt, the Type column contains Text Document, and for a file with the extension .jpg, this column contains JPG File, and so on.

Is it possible to programmatically get the value from the Type column for a given file using C++?

Share Improve this question asked Feb 5 at 13:16 Joe JJoe J 1818 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

Yes, this information is stored in the SHFILEINFOA structure, which can be obtained by calling the SHGetFileInfoA function.

#include <windows.h>
#include <shlobj.h>
#include <iostream>
#include <filesystem>

std::string GetFileType(const std::string& filePath) 
{
    auto fileAttr = std::filesystem::is_directory(filePath) ? FILE_ATTRIBUTE_DIRECTORY : FILE_ATTRIBUTE_NORMAL;

    SHFILEINFOA fileInfo{};
    DWORD_PTR result = SHGetFileInfoA(
        filePath.c_str(),
        fileAttr,
        &fileInfo,
        sizeof(fileInfo),
        SHGFI_TYPENAME | SHGFI_USEFILEATTRIBUTES
    );

    if (result) {
        return fileInfo.szTypeName;
    }
    else {
        return "Unknown file type";
    }
}

int main() {
    std::string filePath = "C:\\Users\\Username\\Desktop\\test.txt";
    std::string fileType = GetFileType(filePath);
    std::cout << "File type: " << fileType << std::endl;
    return 0;
}
发布评论

评论列表(0)

  1. 暂无评论