原本以为这么常用的功能应该是标准C支持的,试了一下才发现不同平台差异挺大。
参考博客:https://blog.csdn.net/u012005313/article/details/50687297
上代码
test_dir.cpp
#include <vector>
#include <algorithm>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <string>
#ifdef linux
# include <unistd.h>
# include <dirent.h>
#else
# include <direct.h>
# include <io.h>
# define getcwd _getcwd
#endif
using namespace std;
vector<string> getFiles(string path)
{
vector<string> files;
string p;
#ifdef _WIN32
_finddata_t file;
long lf;
if ((lf=_findfirst(p.assign(path).append("\\*").c_str(), &file)) == -1) {
cout<<path<<" not found!!!"<<endl;
}
else
{
do {
//cout<< file.name <<endl;
if (strcmp(file.name, ".") == 0 || strcmp(file.name, "..") == 0)
continue;
files.push_back(p.assign(path).append("\\").append(file.name));
}
while(_findnext(lf, &file) == 0);
}
//cout << "bye" << endl;
_findclose(lf);
#endif
#ifdef linux
DIR *dir;
struct dirent *ptr;
char base[1000];
if ((dir=opendir(path.c_str())) == NULL)
{
perror("Open dir error...");
exit(1);
}
while ((ptr=readdir(dir)) != NULL)
{
if(strcmp(ptr->d_name,".")==0 || strcmp(ptr->d_name,"..")==0) ///current dir OR parrent dir
continue;
else if(ptr->d_type == 8) ///file
files.push_back(p.assign(path).append("/").append(ptr->d_name));
else if(ptr->d_type == 10) ///link file
continue;
else if(ptr->d_type == 4) ///dir
continue;
}
closedir(dir);
#endif
sort(files.begin(), files.end());
return files;
}
int main(void)
{
char current_address[500] = {0};
getcwd(current_address, 500);
cout<<"[begin] " << current_address<<endl;
vector<string> files = getFiles((string)current_address);
for (int i=0; i<files.size(); i++)
{
cout<<files[i]<<endl;
}
cout<<"[end]..."<<endl;
return 0;
}
在linux的makefile
CC=g++
test_dir: test_dir.cpp
$(CC) test_dir.cpp -o test_dir
all: test_dir
Window下的nmake文件
CFLAGS = -nologo -O2 -MD -I.
SRCS = .\test_dir.cpp
test_dir.exe: $(SRCS)
cl $(CFLAGS) -Fe$@ $**
del *.obj
all: test_dir.exe
clean:
del /Q *.exe *.obj *.manifest
编译运行都没问题