Xor
Xor

Reputation: 49

CreateFile returns invalid handle value

I'm trying to read file from the directory the exe file is located. The data.txt file is in VS Project directory and when I specify the full path everything works fine.

char curDirectory[MAX_PATH];
GetCurrentDirectory(MAX_PATH, curDirectory);

char filePath[MAX_PATH];

char *name = "\\data.txt";

memcpy(filePath, curDirectory, sizeof(curDirectory));
memcpy(filePath + strlen(curDirectory), name, strlen(name));

HANDLE hFile = CreateFile(filePath, GENERIC_ALL, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

Upvotes: 0

Views: 1209

Answers (1)

David Heffernan
David Heffernan

Reputation: 613572

You don't null terminate the string. Do so by passing strlen(name) + 1 in the second call to memcpy.

Some other observations:

  • When CreateFile fails, you should call GetLastError to obtain an error code.
  • Use strcpy and strcat rather than memcpy when working with strings.
  • That said, your code asks to overrun the buffer. If this really is C++, use std::string and have that class manage buffers.
  • There is no real reason to believe that the executable file is located in the current working directory.

Upvotes: 0

Related Questions