c++ fopen fstream 打开中文路径 获取文件大小
c++ fopen fstream 打开中文路径 获取文件大小
环境需求
需要有iconv的支持
在windows上我用的msys2,安装了mingw,gcc,iconv
若是使用的clion,那么在clionCmakelist中需要添加:
test 为项目名称,改为你的项目名称
target_link_libraries(test iconv)
代码
#include <iostream>
#include <stdio.h>
#include <iconv.h>
#include <string>
#include <string.h>
#include <fstream>
using namespace std;
int UTF8ToGBK(char* input, size_t charInPutLen, char* output, size_t charOutPutLen)
{
int ret =0;
iconv_t cd;
cd = iconv_open("GBK","utf-8");
ret = iconv(cd, &input, &charInPutLen, &output, &charOutPutLen);
iconv_close(cd);
return ret;
}
int UTF8ToGBK(const string& input, string& output)
{
int ret =0;
size_t charInPutLen = input.length();
if( charInPutLen == 0)
return 0;
char *pSource =(char *)input.c_str();
size_t charOutPutLen = 2*charInPutLen;
char *pTemp = new char[charOutPutLen];
memset(pTemp,0,2*charInPutLen);
iconv_t cd;
char *pOut = pTemp ;
cd = iconv_open("utf-8", "GBK");
ret = iconv(cd, &pSource, &charInPutLen, &pTemp, &charOutPutLen);
iconv_close(cd);
output = pOut;
delete []pOut;//注意这里,不能使用delete []pTemp, iconv函数会改变指针pTemp的值
return ret;
}
int GBKToUTF8(char* input, size_t charInPutLen, char* output, size_t charOutPutLen)
{
int ret = 0;
iconv_t cd;
cd = iconv_open("utf-8", "GBK");
ret = iconv(cd, &input, &charInPutLen, &output, &charOutPutLen);
iconv_close(cd);
return ret;
}
int GBKToUTF8(const string& input, string& output)
{
int ret = 0;
size_t charInPutLen = input.length();
if( charInPutLen == 0)
return 0;
size_t charOutPutLen = 2*charInPutLen+1;
char *pTemp = new char[charOutPutLen];
memset(pTemp,0,charOutPutLen);
iconv_t cd;
char *pSource =(char *)input.c_str();
char *pOut = pTemp;
cd = iconv_open("utf-8", "GBK");
ret = iconv(cd, &pSource, &charInPutLen, &pTemp, &charOutPutLen);
iconv_close(cd);
output= pOut;
delete []pOut; //注意这里,不能使用delete []pTemp, iconv函数会改变指针pTemp的值
return ret;
}
long get_file_size(string path)
{
long file_size = 0;
const int max_path_len = 1000;
if(path.size()>=1000)return file_size;
char path1[max_path_len], path2[max_path_len];
memset(path1, 0, sizeof(path1));
memset(path2, 0, sizeof(path2));
memcpy(path1, path.c_str(), path.size());
UTF8ToGBK(path1, max_path_len, path2, max_path_len);
fstream infile;
infile.open(path2, ios::in|ios::binary);
if(infile.is_open())
{
infile.seekg(0, ios::end);
file_size = infile.tellg();
}
infile.close();
return file_size;
}
long get_file_size2(string path)
{
long file_size = 0;
const int max_path_len = 1000;
if(path.size()>=1000)return file_size;
char path1[max_path_len], path2[max_path_len];
memset(path1, 0, sizeof(path1));
memset(path2, 0, sizeof(path2));
memcpy(path1, path.c_str(), path.size());
UTF8ToGBK(path1, max_path_len, path2, max_path_len);
FILE *fp = fopen(path2, "rb");
if(fp!= nullptr)
{
fseek(fp, 0, SEEK_END);
file_size = ftell(fp);
}
fclose(fp);
return file_size;
}
int main()
{
string path = "C:\\Users\\Amazing\\Pictures\\图片\\201001110256-3_1.jpg";
long size = get_file_size(path);
cout<<size<<endl;
return 0;
}