在C++ 11 中使用fopen函数来打开包含中文字符的路径时,需要注意以下两点:
- 确保源代码文件本身也采用了正确的编码格式(如UTF-8)。这样可以确保程序能够正确读取并处理中文字符。
- 将中文路径转换为对应的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;
}