Converting tchar array to string array
I have a program which needs to take the logical drives returned from the GetLogicalDriveString function and store them in a string array for later use in a filepath. I tried doing this directly and it failed. Here's my code:
Code:
#include "stdafx.h"
#include <iostream>
#include <io.h>
#include <time.h>
#include <string>
#include <windows.h>
#include <direct.h>
#include <stdio.h>
#include <tchar.h>
#include <Lmcons.h>
#include <sstream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
CHAR name [ UNLEN + 1 ];
DWORD size = UNLEN + 1;
if (GetUserName( (CHAR*)name, &size ))
wcout << L"Hello, " << name << L"!\n";
else
cout << "Hello, unnamed person!\n";
TCHAR szBuffer[1024];
::GetLogicalDriveStrings(1024, szBuffer);
TCHAR *pch = szBuffer;
while (*pch) {
_tprintf(TEXT("%s\n"), pch);
pch = &pch[_tcslen(pch) + 1];
}
int arraylength = sizeof( pch );
cout << arraylength << endl;
string drive[1025];
int i;
i = 0;
if (i < arraylength)
{
i++;
drive[i] = pch[i];
cout << drive[i] << endl;
}
return 0;
}
Re: Converting tchar array to string array
Quote:
Originally Posted by
Geek_In_Training
I have a program which needs to take the logical drives returned from the GetLogicalDriveString function and store them in a string array for later use in a filepath. I tried doing this directly and it failed.
Where exactly in your code and how did it fail?
Re: Converting tchar array to string array
In a 10 second eyeballing, your code doesn't make a whole lot of sense, but I'm guessing some kind of problem is here.
int arraylength = sizeof( pch );
Re: Converting tchar array to string array
Quote:
Originally Posted by
GCDEF
In a 10 second eyeballing, your code doesn't make a whole lot of sense, but I'm guessing some kind of problem is here.
int arraylength = sizeof( pch );
Good catch, GCDEF! :thumb:
I'm lazy to inspect the code until I know what to look for... ;)
Re: Converting tchar array to string array
Quote:
Originally Posted by
VictorN
Good catch, GCDEF! :thumb:
I'm lazy to inspect the code until I know what to look for... ;)
I just gave it a quick look and that jumped out. The logic looks suspect too, but I didn't make a real effort to follow it.
Re: Converting tchar array to string array
The szBuffer contains a series of null-terminated strings and finally has a double-null termination.
So in the loop the pch always points to a 'normal' zero-terminated TCHAR string which you simply could assign to drives array :
Code:
#ifdef _UNICODE
std::vector<std::wstring> drives;
#else
std::vector<std::string> drives;
#endif
while (*pch)
{
drives.push_back(pch);
pch += _tcslen(pch) + 1;
}