C++文件夹操作

去除后缀

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值