Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ split string with \0 into list

I want to List the logical drives with:

const size_t BUFSIZE = 100;
char buffer[ BUFSIZE ];
memset(buffer,0,BUFSIZE);

//get available drives
DWORD drives = GetLogicalDriveStringsA(BUFSIZE,static_cast<LPSTR>(buffer));

The buffer then contains: 'C',':','\','0'
The buffer after GetLogicalDriveStringA()
Now I want to have a List filled with "C:\","D:\" and so on. Therefore I tried something like this:

std::string tmp(buffer,BUFSIZE);//to split this string then
QStringList drivesList = QString::fromStdString(tmp).split("\0");

But it didn't worked. Is it even possible to split with the delimiter \0? Or is there a way to split by length?

like image 591
Drayke Avatar asked Oct 28 '25 05:10

Drayke


1 Answers

The problem with String::fromStdString(tmp) is that it will create a string only from the first zero-terminated "entry" in your buffer, because that's how standard strings works. It is certainly possible, but you have to do it yourself manually instead.

You can do it by finding the first zero, extract the substring, then in a loop until you find two consecutive zeroes, do just the same.

Pseudoish-code:

current_position = buffer;
while (*current_position != '\0')
{
    end_position = current_position + strlen(current_position);
    // The text between current_position and end_position is the sub-string
    // Extract it and add to list
    current_position = end_position + 1;
}
like image 133
Some programmer dude Avatar answered Oct 31 '25 00:10

Some programmer dude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!