简体   繁体   中英

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'
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?

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM