linux c++获取指定目录下所有特定后缀名的文件名

本文提供了一个使用C++编程语言遍历指定目录下所有.txt文件的示例代码。通过调用opendir和readdir函数,程序能够读取目录中的每个文件,并检查其类型是否为常规文件及后缀名是否为.txt。对于符合条件的文件,将其名称存储到字符串向量中,最后打印出所有找到的.txt文件名。
#include <iostream>
#include <string>
#include <vector>
#include <string.h>
#include <dirent.h>

using namespace std;
int getFiles(const string path, vector<string>& files){
	
	int iFileCnt = 0;
	DIR *dirptr = NULL;
	struct dirent *dirp;
 
	if((dirptr = opendir(path.c_str())) == NULL)//打开一个目录
	{
		return 0;
	}
	while ((dirp = readdir(dirptr)) != NULL)
	{
		if ((dirp->d_type == DT_REG) && 0 ==(strcmp(strchr(dirp->d_name, '.'), ".txt")))//判断是否为文件以及文件后缀名
		{
			files.push_back(dirp->d_name);
		}
		iFileCnt++;
	}
	closedir(dirptr);
	
	return iFileCnt;
}

int main(){
	string path = "the file path";
	vector<string> files;
	getFiles(path,files);
	for(const auto &x: files)
		cout << x << endl;
	return 0;
}
struct dirent
{
   long d_ino; /* inode number 索引节点号 */
   off_t d_off; /* offset to this dirent 在目录文件中的偏移 */
   unsigned short d_reclen; /* length of this d_name 文件名长 */
   unsigned char d_type; /* the type of d_name 文件类型 */
   char d_name [NAME_MAX+1]; /* file name (null-terminated) 文件名,最长255字符 */
}

enum
{
DT_UNKNOWN = 0,
# define DT_UNKNOWN DT_UNKNOWN
DT_FIFO = 1,
# define DT_FIFO DT_FIFO
DT_CHR = 2,
# define DT_CHR DT_CHR
DT_DIR = 4,
# define DT_DIR DT_DIR
DT_BLK = 6,
# define DT_BLK DT_BLK
DT_REG = 8,
# define DT_REG DT_REG
DT_LNK = 10,
# define DT_LNK DT_LNK
DT_SOCK = 12,
# define DT_SOCK DT_SOCK
DT_WHT = 14
# define DT_WHT DT_WHT
};
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值