Hi,
I am trying to list all the files in a drive. when i use "*" instead of "C:\*" in findfirstfile() function then it works fine and lists all the files in the current directory but it does not work when i use "C:\*" and does not list files. can any one tell me plz that how can this can be made correct.thanx

#include "stdafx.h"
#include "fileinfor.h"
#include <iostream>
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include<conio.h>
#include <string>
#include <sstream>
#include <strsafe.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// The one and only application object

CWinApp theApp;
                  
std::string convertWCharArrayToString(const WCHAR * const wcharArray) {
    std::stringstream ss;
 
    int i = 0;
    char c = (char) wcharArray[i];
    while(c != '\0') {
        ss <<c;
        i++;
        c = (char) wcharArray[i];
    }
 
    std::string convert = ss.str();
    return convert;
}


int main()
{
    WIN32_FIND_DATA findFileData;
 
	HANDLE hFind = FindFirstFile((LPCWSTR) "C:\*" , &findFileData);
    
    if(hFind  == INVALID_HANDLE_VALUE) {
        std::cout <<"No files found." <<std::endl;
    } else {
        std::cout <<"Files found." <<std::endl;
    }
    
    int fileNumber = 0;
    std::cout <<fileNumber <<":" <<convertWCharArrayToString(findFileData.cFileName) <<std::endl;
    while(FindNextFile(hFind, &findFileData)) {
        fileNumber++;
        std::cout <<fileNumber <<":" <<convertWCharArrayToString(findFileData.cFileName) <<std::endl;
    }
 
    FindClose(hFind);
 
    char a;
    std::cin>> a;
    return 0;
}

I'm not sure about the code itself, but the problem can be as simple as:
'\' is sort of escape key inside string ("\n", "\t", "\a"...)
If you want to really type '\', you have to write: "\\".
So, instead "C:\*", try "C:\\*"

There are actually 2 things - 1 correctly posted by Sci@phy. You must escape the backslash, so you would enter "C:\\*".

The other is that the function FindFirstFile is expecting a wide character string as input. The cast was set correctly; however, you need to annotate the string constant so it will be interpreted as a wide character string, like this:

HANDLE hFind = FindFirstFile((LPCWSTR) L"C:\\*" , &findFileData);

Notice the "L" in front of the string. This will work.

i have tried this bt it also doesn't work

thanx mcriscolo...it worked:)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.