c++argvtcharfindfirst

C++ _findfirst and TCHAR


I've been given the following code:

int _tmain(int argc, _TCHAR* argv[]) {
    _finddata_t dirEntry;
    intptr_t dirHandle;
    dirHandle = _findfirst("C:/*", &dirEntry);
    int res = (int)dirHandle;
    while(res != -1) {
        cout << dirEntry.name << endl;
        res = _findnext(dirHandle, &dirEntry);
    }
    _findclose(dirHandle);
    cin.get();
   return (0);
}

what this does is printing the name of everything that the given directory (C:) contains. Now I have to make this print out the name of everything in the subdirectories (if there are any) as well. I've got this so far:

int _tmain(int argc, _TCHAR* argv[]) {
    _finddata_t dirEntry;
    intptr_t dirHandle;
    dirHandle = _findfirst(argv[1], &dirEntry);
    vector<string> dirArray;
    int res = (int)dirHandle;
    unsigned int attribT;
    while (res != -1) {
        cout << dirEntry.name << endl;
        res = _findnext(dirHandle, &dirEntry);
        attribT = (dirEntry.attrib >> 4) & 1; //put the fifth bit into a temporary variable
//the fifth bit of attrib says if the current object that the _finddata instance contains is a folder.
        if (attribT) { //if it is indeed a folder, continue (has been tested and confirmed already)
            dirArray.push_back(dirEntry.name);
            cout << "Pass" << endl;
            //res = _findfirst(dirEntry.name, &dirEntry); //needs to get a variable which is the dirEntry.name combined with the directory specified in argv[1].
    }
}
_findclose(dirHandle);
std::cin.get();
return (0);

}

Now I'm not asking for the whole solution (I want to be able to do it on my own) but there is just this one thing I can't get my head around which is the TCHAR* argv. I know argv[1] contains what I put in my project properties under "command arguments", and right now this contains the directory I want to test my application in (C:/users/name/New folder/*), which contains some folders with subfolders and some random files. The argv[1] currently gives the following error:

Error: argument of type "_TCHAR*" is incompatible with parameter of type "const char *"

Now I've googled for the TCHAR and I understand it is either a wchar_t* or a char* depending on using Unicode character set or multi-byte character set (I'm currently using Unicode). I also understand converting is a massive pain. So what I'm asking is: how can I best go around this with the _TCHAR and _findfirst parameter?

I'm planning to concat the dirEntry.name to the argv[1] as well as concatenating a "*" on the end, and using this in another _findfirst. Any comments on my code are appreciated as well since I'm still learning C++.


Solution

  • Use this simple typedef:

    typedef std::basic_string<TCHAR> TCharString;

    Then use TCharString wherever you were using std::string, such as here:

    vector<TCharString> dirArray;
    

    See here for information on std::basic_string.