ahalbert
ahalbert

Reputation: 474

win32 API createFile function: converting to an LPCTSTR

I have the following code that gets the name of the file from a function, then passes it into createFile (expands to createFileA). An earlier question told me to use file.c_str() to convert the filename to an LPCTSTR which createFileA uses. However, this does not work, as the handle to the file is invalid every time createFileA is called. What am I doing wrong?

string file = getFilename();
HANDLE hf = CreateFile(file.c_str(),GENERIC_READ | GENERIC_WRITE,(DWORD) 0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,(HANDLE) NULL);
if (hf == INVALID_HANDLE_VALUE)
   {
     MessageBox( hwnd,"CreateFile","Error", MB_OK);
   }

Upvotes: 0

Views: 4261

Answers (3)

user1348669
user1348669

Reputation:

I just noticed that if you used the following code

std::stringstream ss; ss << "C:\filename.txt" <

Then do ss.str() to get to std::string. Then if you do c_str() to pass to CreateFile

This will not work with CreateFile and its very hard to track the root cause but its the "endl;", it got streamed into the buffer and so the path will be invalid

It will always report error 123 invalid file name

It also happens with the wide version.

Upvotes: 0

JaredPar
JaredPar

Reputation: 755131

Based on the comments on the question the problem is that the name you are providing contains a :. This character is illegal for file names in windows and is the source of your problem. Remove that character and the code should work fine

Upvotes: 0

Martin Beckett
Martin Beckett

Reputation: 96139

If it compiles then .c_str() must be the correct type!

The most common reason for ERROR_INVALID_NAME is an illegal character in the filename, an extra ":" or a tab or you are using a reserved filename. Check the value of filename

Upvotes: 2

Related Questions