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

  • Post author:
  • Post category:linux


#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
};



版权声明:本文为Betterc5原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。