如何在txt文件中获取imagepath的根文件夹名称

时间:2015-06-20 16:01:45

标签: c++ visual-studio-2012

我在C ++中有一个关于获取由" \"分隔的名称的问题。我有一个文本文件存储图像的完整路径及其标签(只有1,2 ...),如

Image_align\Russian\1.jpg;1
Image_align\USA\2.jpg;1
Image_align\China\3.jpg;2

我想获取图片名称及其根文件夹名称。例如。我有形象' 1.jpg'它的根文件夹是' Russia'。我做了一些事情,我完成了获取文件名。现在,我仍然是它的根文件夹。你可以让我用C ++找到它吗?提前谢谢

这是我尝试过的代码

std::ifstream
file("database.txt");
char separator = ';'; //Filename and label separate by ";"
string imagepath; //'Image_align\Russian\1.jpg'
string label;
while (std::getline(file, content))
{
stringstream liness(content);
getline(liness, imagepath, separator);
Mat image = imread(imagepath);
const size_t last_slash_idx = imagepath.find_last_of("\\/");
if (std::string::npos != last_slash_idx)
{
    imagepath.erase(0, last_slash_idx + 1);
}
string imagename=imagepath;
//Now I want to get the its root folder such as 'Russia', 'USA'..

2 个答案:

答案 0 :(得分:2)

我正在推销一个稍微聪明的标记器

void multiparse(string overtoken, vector<string> &tokens, const char * delims)
{
    stringstream ss(overtoken);
    string token;
    while (getline(ss, token, delims[0]))
    {
        if (delims[1] == '\0' || token.length() == 0)
        {
            tokens.push_back(token);
        }
        else
        {
            multiparse(token, tokens, &delims[1]);
        }
    }
}

用法:

while (std::getline(file, content))
{
    stringstream liness(content);
    getline(liness, imagepath, separator);
    Mat image = imread(imagepath);
    vector<string> tokens;
    multiparse(imagepath, tokens, "/\\");
    string imagename;
    string rootfolder;
    if (tokens.size() >= 2)
    {     
        vector<string>::iterator it = tokens.end();
        --it;
        imagename = *it;
        --it;
        rootfolder = *it;
        // do stuff
    }
    else
    {  
        cerr << "Parsed bad line" << endl;
        // appropriate failure response
    }
}

答案 1 :(得分:1)

如果您的项目可以使用Win32 API,那么PathRemoveFileSpec应该是一种方法。