发布日期:2018-03-26
使用C或者C++时,我怎样才能在目录中获得文件列表?+ 查看更多
使用C或者C++时,我怎样才能在目录中获得文件列表?
+ 查看更多
发布日期:2018-02-26 10:20
分类:CPlusPlus
浏览次数:150
如下:
我怎样才能确定目录的文件列表来自于我的C或C++代码?
我不可以执行'ls'命令也不能解析我的程序运行结果.
回答:
在一个小而简单的工作中,我不使用boost而是用了对windows用户也适用的dirent.h
DIR *dir; struct dirent *ent; if ((dir = opendir ("c:\\src\\")) != NULL) { /* print all the files and directories within directory */ while ((ent = readdir (dir)) != NULL) { printf ("%s\n", ent->d_name); } closedir (dir); } else { /* could not open directory */ perror (""); return EXIT_FAILURE; }
它只是一个小的头文件,可以完成绝大多数简单你需要的功能,而不需要使用像boost那样大的基于模版的方法(无意冒犯,我喜欢boost!)
还有一些其它实现方式哦。
这段代码是跨平台的
bool find_file( const path & dir_path, // in this directory, const std::string & file_name, // search for this name, path & path_found ) // placing path here if found { if ( !exists( dir_path ) ) return false; directory_iterator end_itr; // default construction yields past-the-end for ( directory_iterator itr( dir_path ); itr != end_itr; ++itr ) { if ( is_directory(itr->status()) ) { if ( find_file( itr->path(), file_name, path_found ) ) return true; } else if ( itr->leaf() == file_name ) // see below { path_found = itr->path(); return true; } } return false; }
Unix/Linux系统
len = strlen(name); dirp = opendir("."); while ((dp = readdir(dirp)) != NULL) if (dp->d_namlen == len && !strcmp(dp->d_name, name)) { (void)closedir(dirp); return FOUND; } (void)closedir(dirp); return NOT_FOUND;
WINDOWS系统
#include#include #include void _tmain(int argc, TCHAR *argv[]) { WIN32_FIND_DATA FindFileData; HANDLE hFind; if( argc != 2 ) { _tprintf(TEXT("Usage: %s [target_file]\n"), argv[0]); return; } _tprintf (TEXT("Target file is %s\n"), argv[1]); hFind = FindFirstFile(argv[1], &FindFileData); if (hFind == INVALID_HANDLE_VALUE) { printf ("FindFirstFile failed (%d)\n", GetLastError()); return; } else { _tprintf (TEXT("The first file found is %s\n"), FindFileData.cFileName); FindClose(hFind); } }