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();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM