Converting 'const char*' to 'LPCTSTR' for CreateDirectory

ProGirlXOXO picture ProGirlXOXO · Jan 17, 2013 · Viewed 28.6k times · Source
#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'

  1. How do I make this conversion?
  2. 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?
  3. I am terrible at data types and conversions, is there a good explanation for 5 year olds out there?

Answer

Remy Lebeau picture Remy Lebeau · Jan 17, 2013

std::string is a class that holds char-based data. To pass a std::string data to API functions, you have to use its c_str() method to get a char* pointer to the string's actual data.

CreateDirectory() takes a TCHAR* as input. If UNICODE is defined, TCHAR maps to wchar_t, otherwise it maps to char instead. If you need to stick with std::string but do not want to make your code UNICODE-aware, then use CreateDirectoryA() instead, eg:

#include "stdafx.h"
#include <string>
#include <windows.h>

int main()
{
    std::string FilePath = "C:\\Documents and Settings\\whatever";
    CreateDirectoryA(FilePath.c_str(), NULL);
    return 0;
}

To make this code TCHAR-aware, you can do this instead:

#include "stdafx.h"
#include <string>
#include <windows.h>

int main()
{
    std::basic_string<TCHAR> FilePath = TEXT("C:\\Documents and Settings\\whatever");
    CreateDirectory(FilePath.c_str(), NULL);
    return 0;
}

However, Ansi-based OS versions are long dead, everything is Unicode nowadays. TCHAR should not be used in new code anymore:

#include "stdafx.h"
#include <string>
#include <windows.h>

int main()
{
    std::wstring FilePath = L"C:\\Documents and Settings\\whatever";
    CreateDirectoryW(FilePath.c_str(), NULL);
    return 0;
}