Error C2664: 'strcpy' : cannot convert parameter 2 from 'const wchar_t [9]' to 'const char *'.How to solve this error?

匿名 (未验证) 提交于 2019-12-03 01:12:01

问题:

How can I get rid of this error and other while compiling the below code?

#include "stdafx.h" #include <string> #include <vector> #include <windows.h> #include <atlstr.h> #include <tchar.h> #include <stdio.h> #define MAX_PATH_LENGTH 256  int main(int argc, char *argv[]) {   int i;   char path[300];   bool FindFilesFromFolder();    getchar();    return 0;   }   bool FindFilesFromFolder()  {  HANDLE            hFile;  WIN32_FIND_DATA   FindFileData;  std::vector<char> fileList;    char chFolderpath[_MAX_PATH];   CString strExtension   = _T("*.B11");    strcpy(chFolderpath, _T("F:\\test\\"));   strcat(chFolderpath, strExtension);   hFile = FindFirstFile(chFolderpath, &FindFileData);    if (hFile == INVALID_HANDLE_VALUE) {    AfxMessageBox(_T("Inavlid file handle."));   return false;   }    CString filepath;     do    {      filepath.Format(_T("%s%s"), _T("F:\\test\\"), FindFileData.cFileName);     fileList.push_back(filepath);     } while(FindNextFile(hFile, &FindFileData));      return true;    } 

Yes this is an example to know the correct usage of findfirstfile(). I got strcpy errors too.

Error:error C2664: 'strcpy' : cannot convert parameter 2 from 'const wchar_t [9]' to 'const char *'. Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast.

Error: error C2664: 'strcat' : cannot convert parameter 2 from 'ATL::CString' to 'const char *'. No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called.

Error:error C2664: 'std::vector<_Ty>::push_back' : cannot convert parameter 1 from 'ATL::CString' to 'const char &' with

It gives all conversion errors; how to solve these errors?

回答1:

Your title says strcpy but your code and errors have FindFirstFile?

Anyway, declaring your buffer like this will help:

TCHAR chFolderpath[_MAX_PATH]; 

Then you will want to use _tcscpy and _tcscat instead of strcpy and strcat. Even better, #include <strsafe.h> and use the string functions that protect against buffer overrun.

Regarding AfxMessageBox, this is not a standard Windows function. It's part of MFC, I suppose you cut and pasted from an example that used MFC. Windows has a MessageBox function which you can use, but you'll need to supply all the parameters (parent window, message, title, buttons).



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!