#include "stdafx.h"
#include <string>
#include <windows.h>
using namespace std;
int main()
{
string FilePath = "C:\\Documents and Settings\\whatever";
CreateDirectory(FilePath, NULL);
return 0;
}
Error: error C2664: 'CreateDirectory' : cannot convert parameter 1 from 'const char *' to 'LPCTSTR'
- How do I make this conversion?
- The next step is to set today's date as a string or char and concatenate it with the filepath. Will this change how I do step 1?
- I am terrible at data types and conversions, is there a good explanation for 5 year olds out there?
std::string
is a class that holdschar
-based data. To pass astd::string
data to API functions, you have to use itsc_str()
method to get achar*
pointer to the string's actual data.CreateDirectory()
takes aTCHAR*
as input. IfUNICODE
is defined,TCHAR
maps towchar_t
, otherwise it maps tochar
instead. If you need to stick withstd::string
but do not want to make your codeUNICODE
-aware, then useCreateDirectoryA()
instead, eg:To make this code
TCHAR
-aware, you can do this instead:However, Ansi-based OS versions are long dead, everything is Unicode nowadays.
TCHAR
should not be used in new code anymore:If you're not building a Unicode executable, calling
c_str()
on the std::string will result in aconst char*
(aka non-Unicode LPCTSTR) that you can pass intoCreateDirectory
().The code would look like this:
Please note that this will result in a compile error if you're trying to build a Unicode executable.
If you have to append to
FilePath
I would recommend that you either continue to usestd::string
or use Microsoft'sCString
to do the string manipulation as that's less painful that doing it the C way and juggling raw char*. Personally I would usestd::string
unless you are already in an MFC application that uses CString.