windows _wfopen 和 linux wfopen,char 转 wchar_t

windows _wfopen 和 linux wfopen 代码:

windows:

bool UTF8ToUnicode(const char* UTF8, wchar_t* strUnicode)
{
    DWORD dwUnicodeLen;    //转换后Unicode的长度
    TCHAR *pwText;      //保存Unicode的指针
    // wchar_t* strUnicode;    //返回值
    //获得转换后的长度,并分配内存
    dwUnicodeLen = MultiByteToWideChar(CP_UTF8,0,UTF8,-1,NULL,0);
    pwText = new TCHAR[dwUnicodeLen];
    if(!pwText)
    {
        return false;
    }
    //转为Unicode
    MultiByteToWideChar(CP_UTF8,0,UTF8,-1,pwText,dwUnicodeLen);
    //转为CString
    wcscpy(strUnicode, pwText);
    //清除内存
    delete[] pwText;
    return true;
}

int test(string path)
{
	 //  string  bmpName = "C:\\Users\\Administrator\\Desktop\\test.bmp";
    string  bmpName = path;

    char* bmp = new char[SUBTITLE_DATA_SIZE];
	if (!bmp) {
		cout << "bad malloc" << endl;
		return 0;
	}
    int bfSize = SUBTITLE_DATA_SIZE;

    wchar_t strUnicode[260];
    UTF8ToUnicode(bmpName.c_str(), strUnicode);
    FILE *fp;
    if ((fp = _wfopen(strUnicode, L"rb")) == NULL)   //  以二进制的方式打开文件   //
    {
        cout << "The file " << bmpName << "was not opened" << endl;
        return 0;
    }

	if (fseek(fp, 0, 0))  
	{
		cout << "跳转失败" << endl;
		return 0;
	}

	unsigned int len = fread(bmp, 1, bfSize, fp);
	fclose(fp);
    return 0;
}

linux:

int char_to_wchar(wchar_t *pDest, const char *pSrc)
{
    int len = 0;
    int ret = 0;
    len = strlen(pSrc) + 1;
    if(len <= 1)
        return 0;
    ret = mbstowcs(pDest, pSrc, len);
    return ret;
}

#define MAX_PATH 1024

FILE* wfopen(const wchar_t* filename, const wchar_t* mode)
{
    char fn[MAX_PATH];
    char m[MAX_PATH];
    wcstombs(fn, filename, MAX_PATH);
    wcstombs(m, mode, MAX_PATH);
    return fopen(fn, m);
}

int test(string path)
{

    string  bmpName = path;
    char* bmp = new char[SUBTITLE_DATA_SIZE];
    if (!bmp) {
        cout << "bad malloc" << endl;
        return 0;
    }
    int bfSize = SUBTITLE_DATA_SIZE;
    wchar_t strUnicode[260];

    memset(strUnicode, 0x00, sizeof(strUnicode));
    setlocale(LC_CTYPE, "zh_CN.utf8");
    char_to_wchar(strUnicode, bmpName.c_str());


    FILE* fp = wfopen(strUnicode, L"rb");
    if(fp)
        printf("File open successeed!\n");
    else
        printf("File open failed!\n");

   if (fseek(fp, 0, 0)) 
   {
       cout << "跳转失败" << endl;
       return 0;
   }

   unsigned int len = fread(bmp, 1, bfSize, fp);
   fclose(fp);
   return 0;
}


版权声明:本文为qq_40015157原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。