[英]How to get root folder name of imagepath in txt file
I have a question in C++ about get name that seperated by "\\". 我在C ++中有一个问题,关于用“ \\”分隔的获取名称。 I have a text file that store full path of image and its labels (just 1,2...) such as
我有一个文本文件,存储图像的完整路径及其标签(仅1,2 ...),例如
Image_align\Russian\1.jpg;1
Image_align\USA\2.jpg;1
Image_align\China\3.jpg;2
I want to get the image name and its root folder name. 我想获取图像名称及其根文件夹名称。 For example.
例如。 I have image '1.jpg' and its root folder is 'Russia'.
我有图像“ 1.jpg”,其根文件夹是“ Russia”。 I do something and I done to get the file name.
我做了一些事情,然后做得到了文件名。 Now, I remain its root folder.
现在,我保留其根文件夹。 Could you have me to find it by C++?
您能否让我用C ++找到它? Thank in advance
预先感谢
This is my code that I tried 这是我尝试过的代码
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'..
I'm pitching a slightly smarter tokenizer 我正在推出一个更智能的令牌生成器
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]);
}
}
}
usage: 用法:
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
}
}
如果您的项目可以使用Win32 API, 则应该使用PathRemoveFileSpec 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.