Question

#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?
Was it helpful?

Solution

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;
}

OTHER TIPS

If you're not building a Unicode executable, calling c_str() on the std::string will result in a const char* (aka non-Unicode LPCTSTR) that you can pass into CreateDirectory().

The code would look like this:

CreateDirectory(FilePath.c_str(), NULL):

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 use std::string or use Microsoft's CString to do the string manipulation as that's less painful that doing it the C way and juggling raw char*. Personally I would use std::string unless you are already in an MFC application that uses CString.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top