Windows中使用CopyFile函数复制文件,出现string转LPCTSTR问题(附代码)

原因:

同一张图片,用imread读取,imwrite重新写入另外一个文件夹,然后再次读取发现前后异常,这是因为读取后转成Mat格式,然后写入转成图片格式,这个过程会对图片产生损失。

因此后来采用直接复制图片路径,由于我的代码中图片路径是string,但是window.h头文件中的CopyFile()函数的参数是LPCTSTR格式,具体如下:

BOOL CopyFile( 

LPCTSTR lpExistingFileName, // pointer to name of an existing file 
LPCTSTR lpNewFileName, // pointer to filename to copy to 
BOOL bFailIfExists // flag for operation if file exists 
); 
其中各参数的意义: 
LPCTSTR lpExistingFileName, // 你要拷贝的源文件名 
LPCTSTR lpNewFileName, // 你要拷贝的目标文件名 
BOOL bFailIfExists // 如果目标已经存在,不拷贝(True)并返回False,覆盖目标(false)。

因此需要将string转成LPCTSTR格式,但是C++中并没有强制转换的函数。

 

解决方案:

将string转换成wstring,再转换成LPCTSTR,具体实现代码如下:

std::wstring s2ws(const std::string& s){

 int len;

 int slength = (int)s.length() + 1;

 len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);

 wchar_t* buf = new wchar_t[len];

 MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);

 std::wstring r(buf);

 delete[] buf;

 return r.c_str();

}

 

std::string s;

std::wstring stemp = s2ws(s); 

LPCWSTR result = stemp.c_str();

 

posted @ 2017-07-28 12:14  两猿社  阅读(2082)  评论(0编辑  收藏  举报