//FileList.h
////
//获取目录路径下面所有文件的内容
//适用于linux和windows系统
////
#ifndef _FILELIST_H_
#define _FILELIST_H_
#include <
string>
#include <vector>
#include <iostream>
using namespace std;
#ifdef _WIN32
#include <Windows.h>
#include <strsafe.h>
#else
#include <dirent.h>
#endif
//
//获取指定目录下所有文件的文件名,不包括文件夹,在GetFileFromDir中使用
//strDir: 输入,目录路径
//FileDirList: 输出,文件路径列表
//返回:空
//
vector<
string> GetFileNameFromDir(
string strDir)
{
vector<
string>
vFileDirList;
#ifdef _WIN32
WIN32_FIND_DATAA ffd;
//LARGE_INTEGER filesize;
string szDir;
//size_t length_of_arg;
HANDLE hFind =
INVALID_HANDLE_VALUE;
DWORD dwError=
0;
szDir=strDir+
"\\*.jpg";
hFind = FindFirstFileA(szDir.c_str(), &
ffd);
if (INVALID_HANDLE_VALUE ==
hFind)
{
cout<<
"get file name error"<<
endl;
return vFileDirList;
}
do
{
if (!(ffd.dwFileAttributes &
FILE_ATTRIBUTE_DIRECTORY))
{
string filename=ffd.cFileName;
//(const char*)
string filedir=strDir+
"\\"+
filename;
vFileDirList.push_back(filedir);
}
}while (FindNextFileA(hFind, &ffd) !=
0);
dwError =
GetLastError();
if (dwError !=
ERROR_NO_MORE_FILES)
{
cout<<
"FindFirstFile error"<<
endl;
return vFileDirList;
}
FindClose(hFind);
#else
DIR *
dir;
struct dirent *
ptr;
dir =
opendir(strDir.c_str());
while( (ptr = readdir(dir)) !=
NULL)
{
string filename =
string(ptr->
d_name);
if (filename ==
"." || filename ==
".."){
continue;
}
string path = strDir +
string(
"/") +
filename;
vFileDirList.push_back(path);
}
closedir(dir);
sort(vFileDirList.begin(), vFileDirList.end());
#endif
return vFileDirList;
}
#endif
int main(
void)
{
string strDir;
vector<
string> files = GetFileNameFromDir(
strDir);
for (
int i =
0; i < files.size(); ++
i){
cout << files[i] <<
endl;
}
return 0;
}
转载请注明原文地址: https://ju.6miu.com/read-7688.html