获取程序所在目录&列举目录下文件和文件夹--C++实现

话不多说, 直接上代码

CommonFunc.h

#pragma once
#include <direct.h>
using namespace std;

//枚举指定路径下文件,c++方法
void listFiles(char* dir, vector<char*>& vecSzFilename);
//枚举指定路径下文件夹,c++方法
void listDir(char* dir, vector<char*>& vecSzDir);
//获取程序所在文件夹,c++方法
int getWorkDir(char* szProgramPath);

CommonFunc.cpp文件

#include "CommonFunc.h"
//获取当前程序绝对路径
int getWorkDir(char* szProgramPath)
{
	char szPath[_MAX_PATH] = { 0 };
	char szDrive[_MAX_DRIVE] = { 0 };
	char szDir[_MAX_DIR] = { 0 };
	char szFname[_MAX_FNAME] = { 0 };
	char szExt[_MAX_EXT] = { 0 };

	GetModuleFileNameA(NULL, szPath, sizeof(szPath));
	//ZeroMemory(szProgramPath, strlen(szProgramPath));
	_splitpath_s(szPath, szDrive, szDir, szFname, szExt);
	sprintf_s(szProgramPath, _MAX_PATH, "%s%s", szDrive, szDir);

	return 0;
}
//枚举指定路径下文件名, 保存到vector中
void listFiles(char * dir, vector<char*>& vecSzFilename)
{
	char szDir[_MAX_PATH] = { 0 };
	sprintf_s(szDir, _MAX_PATH, "%s%s", dir, "*.*");			
	intptr_t handle;
	_finddata_t findData;

	handle = _findfirst(szDir, &findData); 
	if (handle == -1)
	{
		cout << "Failed to find first file!\n";
		return;
	}

	do
	{
		if (findData.attrib & _A_SUBDIR
			|| strcmp(findData.name, ".") == 0
			|| strcmp(findData.name, "..") == 0
			)    
		{
			//cout << findData.name << "\t<dir>\n";
		}
		else
		{
			//cout << findData.name << "\t" << findData.size << endl;
			char* pBuffer = new char[_MAX_PATH]();
			sprintf_s(pBuffer, _MAX_PATH, "%s%s", dir, findData.name);
			vecSzFilename.push_back(pBuffer);
		}
	} while (_findnext(handle, &findData) == 0);    

	//cout << "Done!\n";
	_findclose(handle);    // ¹Ø±ÕËÑË÷¾ä±ú
}
//枚举指定路径下文件夹, 保存到vector中
void listDir(char * dir, vector<char*>& vecSzDir)
{
	char szDir[_MAX_PATH] = { 0 };
	sprintf_s(szDir, _MAX_PATH, "%s%s", dir, "*.*");			
	intptr_t handle;
	_finddata_t findData;

	handle = _findfirst(szDir, &findData);    
	if (handle == -1)
	{
		cout << "Failed to find first file!\n";
		return;
	}
	do
	{
		if (findData.attrib & _A_SUBDIR && 
			strcmp(findData.name, ".") != 0 &&
			strcmp(findData.name, "..") != 0)
		{
			cout << findData.name << "\t<dir>\n";
			char* pBuffer = new char[_MAX_PATH]();
			sprintf_s(pBuffer, _MAX_PATH, "%s%s%s", dir, findData.name, "\\");
			vecSzDir.push_back(pBuffer);
		}
		else
		{
			cout << findData.name << "\t" << findData.size << endl;
			//char* pBuffer = new char[_MAX_PATH]();
			//sprintf_s(pBuffer, _MAX_PATH, "%s%s", dir, findData.name);
			//vecSzFilename.push_back(pBuffer);
		}
	} while (_findnext(handle, &findData) == 0);    
	_findclose(handle);    // ¹Ø±ÕËÑË÷¾ä±ú
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值