去除后缀
void main()
{
string a = "123_1.jpg";
string b = a.substr(0, a.rfind("_"));
cout << a << endl << b << endl;
}
获取string最后一个一个字符
void main()
{
string a = "123_1.jpg";
string::iterator ite = a.end()-1;//a.end()是指向string的尾后
cout << *ite << endl;
}
读取文件夹中所有文件名
#include <stdio.h>
#include <iostream>
#include <string> //忘了这个cout就无法输出string类型。。。
#include <vector>
#include <io.h> //_finddata_t,_findfirst,_findnext,_findclose要用
using namespace std;
//查找的文件夹路径,支持通配符
const char *dir_path = "D:\\code\\c\\Project1\\Project1\\test\\*.xml"; //指向常量的指针
int main()
{
long handle; //用于查找的句柄
struct _finddata_t fileinfo; //存储文件信息的结构体
vector<string> all_filename;//用于存储所有文件名的vector
遍历文件夹
handle = _findfirst(dir_path, &fileinfo); //第一次查找。若查找失败,返回-1
if (handle == -1)
{
return -1;
}
all_filename.push_back(fileinfo.name); //存入向量里
while (!_findnext(handle, &fileinfo)) //循环查找其他符合的文件,直到找完
{
all_filename.push_back(fileinfo.name);//存入向量
}
_findclose(handle);//不写好像也没影响,还是写了吧
迭代器遍历存有所有文件名的vector,并输出
for (vector<string>::iterator ite = all_filename.begin(); ite != all_filename.end(); ite++)
{
cout << *ite << endl;
}
return 0;
}
读取文件夹下所有文件夹名
#include <iostream>
#include <string>
#include <vector>
#include <io.h>
using namespace std;
vector<string> dir(string path)
{
long hFile = 0;
struct _finddata_t fileInfo;
vector<string> folder_1;//一级文件夹下所有文件(夹)名
hFile = _findfirst(path.append("*").c_str(), &fileInfo);//在路径末尾添加通配符
if ( hFile == -1)
{
exit(0);
}
folder_1.push_back(fileInfo.name);
while (_findnext(hFile, &fileInfo) == 0)//如果找到下一个还有,那就继续
{
folder_1.push_back(fileInfo.name);
}
_findclose(hFile);
return folder_1;
}
int main()
{
//要遍历的目录
string path = "D:\\code\\aaa\\aaa\\type\\";
vector<string> folder_1_name=dir(path);//存放1级目录文件(夹)名
vector<vector<string>> all; //存放所有子目录的二维vector
int num = folder_1_name.size() - 2;//folder_1_name还包含.和..2个目录,去除
for (vector<string>::iterator ite = folder_1_name.begin(); ite != folder_1_name.end(); ite++)
{
cout << *ite << endl;
}
return 0;
}