开发者

how to convert WIN32_FIND_DATA to string?

im using WIN32_FIND_DATA to store the data findfirstfile outputs. i want the file location (C:\file) as a string but i don't know how to get it or any other data from it.

Edit: here is my code

PTSTR pszFileName; 
PTSTR pszFileName2[100];
if (search_handle) 
{ 
    do 
    {
        pszFileName = file.cFileName;
        pszFileName2[loop] = pszFileName;
        Sleep(100);
        loop++;

        std::wcout << file.cFi开发者_如何学编程leName << std::endl;
    }
    while(FindNextFile(search_handle,&file)); 

    CloseHandle(search_handle); 
}


WIN32_FIND_DATA is a struct. Check out the cFileName member.

For example:

WIN32_FIND_DATA FindData = {0};
HANDLE hFind = FindFirstFile(pszPattern, &FindData);

if (hFind != INVALID_HANDLE_VALUE)
{
   do
   {
      PTSTR pszFileName = FindData.cFileName;

      // TODO: Use pszFileName in some way...

   } while (FindNextFile(hFind, &FindData));

   FindClose(hFind);
}

Update in response to comments

In this example the storage for the string is on the stack, and the same buffer is used for every call. This means that every FindNextFile() overwrites the previous string. You will have to make a copy of the string.

Since you're using C++ and classes in std I suggest you store it in std::string (or better yet, make sure you define UNICODE and _UNICODE and use wstring.) Initializing a new string class will do the allocation and copying on your behalf.

Alternatively you can copy the string using the typical C techniques (for example: using malloc + memcpy, strdup, or similar), but it sounds like you might want a refresher in strings, pointers, and memory allocation in C before you get to that.

By the way -- to check for error, your code compares the find handle against NULL; this is incorrect. FindFirstFile() returns INVALID_HANDLE_VALUE (which works out to (HANDLE)-1) on failure. Additionally, to close the handle you will want to use FindClose(), and not CloseHandle(). (A "find handle" isn't really a handle to a kernel object in the same sense that a file handle, handle to a module, or a thread or process handle is. They've just overloaded the type.)


The problem is that you're storing the address of the filename in your array. Each time that FindNextFile() is called, it replaces the data in the struct with the information for the next file. You need to allocate memory for the string in your array, and then copy the string from the structure to your array (using something like strncpy_s(), probably).

Your code is just storing the pointer to the filename member of the struct, once per found file. If you look at the address each element in the array is pointing to, they're all pointing to the same place.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜