c 遍历文件夹

int GetDataFileList(string sDataPath, set<string> &setDataFileList)
{

	DIR *dp = NULL;
	struct dirent *entry = NULL;
	struct stat statbuf;
	int iRet = 0;

	dp = opendir(sDataPath.c_str());
	if(NULL == dp)	
	{
		LOG("opendir [%s] error.\n", sDataPath.c_str());
		return -1;
	}

	chdir(sDataPath.c_str());
	while(NULL != (entry = readdir(dp)))
	{
		if((0 == strncmp(".", entry->d_name, 4)) || (0 == strncmp("..", entry->d_name, 4)))
			continue;

		lstat(entry->d_name, &statbuf);
		if(!S_ISDIR(statbuf.st_mode))
		{
			LOG("Get data file [%s].\n", entry->d_name);
			setDataFileList.insert(entry->d_name);
		}
		else
		{
			LOG("file [%s] is path.\n", entry->d_name);
			continue;
		}
	}
	chdir;  //一定要记得退出文件夹,否则由于pwd的改变将导致后面打开相对路径文件出错.
	iRet = closedir(dp);
	LOG("close dir return : [%d].\n", iRet);
	
	return 0;
}

你可能感兴趣的:(c 遍历文件夹)