Help with FindFirstFile

R

Rich Strang

Hi group

I have just got the FindFirstFile function working in my small tutorial app,
the problem is that I can only seem to get it working when I hard code the
search string. I have defined a string str1 but I get a conversion error
when passing it to the function. Also when I attempt to print a string I
get a memory error: "Memory could not be read".

I have included the code below for you all to see, it is just a subset of
the code I am using.

I would be *very* grateful of any pointers you could provide me with to
fixing this problem.

Kind regards

Rich Strang

#define _WIN32_WINNT 0x0400
#include <windows.h>
#include <stdio.h>
#include <string>
using namespace std;

int main(int argc, char *argv[])
{
WIN32_FIND_DATA FindFileData;
HANDLE hFind;

string str1 = "main.cpp";

//printf ("Target file is %s.\n", str1);
hFind = FindFirstFile(str1, &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
{
printf ("Invalid File Handle. GetLastError reports %d\n", GetLastError
());
return (0);
}
else
{
printf ("The first file found is %s\n", FindFileData.cFileName);
FindClose(hFind);
return (1);
}
}
 
R

Ron Natalie

Rich Strang said:
string str1 = "main.cpp";

FindFirstFile takes a const char* (or perhaps a const wchar_t*) not a string.
hFind = FindFirstFile(str1.c_str(), &FindFileData);
 
M

Maximus

Rich Strang said:
Hi group

I have just got the FindFirstFile function working in my small tutorial app,
the problem is that I can only seem to get it working when I hard code the
search string. I have defined a string str1 but I get a conversion error
when passing it to the function. Also when I attempt to print a string I
get a memory error: "Memory could not be read".

I have included the code below for you all to see, it is just a subset of
the code I am using.

I would be *very* grateful of any pointers you could provide me with to
fixing this problem.

Kind regards

Rich Strang

#define _WIN32_WINNT 0x0400
#include <windows.h>
#include <stdio.h>
#include <string>
using namespace std;

int main(int argc, char *argv[])
{
WIN32_FIND_DATA FindFileData;
HANDLE hFind;

string str1 = "main.cpp";

//printf ("Target file is %s.\n", str1);
hFind = FindFirstFile(str1, &FindFileData);

Try this:
printf ("Target file is %s.\n", str1.c_str());
hFind = FindFirstFile(str1.c_str(), &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
{
printf ("Invalid File Handle. GetLastError reports %d\n", GetLastError
());
return (0);
}
else
{
printf ("The first file found is %s\n", FindFileData.cFileName);
FindClose(hFind);
return (1);
}
}



Max.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,135
Latest member
VeronaShap
Top