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 <string>
#include <sstream>
#include <strsafe.h>
#ifdef _DEBUG
#define new DEBUG_NEW

// 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;
        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)) {
        std::cout <<fileNumber <<":" <<convertWCharArrayToString(findFileData.cFileName) <<std::endl;
    char a;
    std::cin>> a;
    return 0;
8 Years
Discussion Span
Last Post by chanda gul

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.