C++ 11 fopen 支持打开带中文的路径

15 篇文章 0 订阅

在C++ 11 中使用fopen函数来打开包含中文字符的路径时,需要注意以下两点:

  1. 确保源代码文件本身也采用了正确的编码格式(如UTF-8)。这样可以确保程序能够正确读取并处理中文字符。
  2. 将中文路径转换为对应的Unicode或者多字节字符集进行传入。

1.定义std::string转宽字符的一些函数:

#include <codecvt>

/// <summary>
/// 字符串转宽字符串,宽字符串转字符串
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
static std::wstring Str2WStr(const std::string& input);

static std::string WStr2Str(const std::wstring& input);

std::wstring BaseFuncs::Str2WStr(const std::string& input)
{
    std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
    return converter.from_bytes(input);
}

std::string BaseFuncs::WStr2Str(const std::wstring& input)
{
    std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
    return converter.to_bytes(input);
}

2.文件处理函数
读取文件的大小

long BaseFuncs::ReadFileSize(std::string filePath)
{
    long fileSize = -1;
    std::wstring tmpStr = BaseFuncs::Str2WStr(filePath);

    //通过宽字节模式支持路径中包含中文的情况
    FILE* fp;
    if ((fp = _wfopen(tmpStr.c_str(), L"rb")) == NULL)
    {
        return fileSize;
    }

    if (fseek(fp, 0L, SEEK_END) == 0)
    {
        fileSize = ftell(fp);
    }

    fclose(fp);
    return fileSize;
}

读取文件内容

long fileSize = BaseFuncs::ReadFileSize(fullPath);
std::shared_ptr<char[]> spFileData(new char[fileSize], std::default_delete<char[]>());

bool BaseFuncs::ReadFileData(std::string filePath, char* fileData)
{
        std::wstring tmpStr = BaseFuncs::Str2WStr(filePath);

        FILE* fp;

        if ((fp = _wfopen(tmpStr.c_str(), L"rb")) == NULL)
        {
                return false;
        }

        //文件指针的位置回到文件的起始位置
        rewind(fp);

        跳过前2个字节
        //fseek(fp, 2, SEEK_SET);

        //每次读取的buffer设置为16K
        char buffer[1024 * 16];
        size_t count = 0;
        int totalCount = 0;
        while ((count = fread(buffer, sizeof(char), sizeof(buffer), fp)) > 0)
        {
                memcpy(fileData + totalCount, buffer, count);
                totalCount = totalCount + (int)count;
        }

        fclose(fp);

        return true;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值