如何获取 C++ 目录中的文件列表?
如何获取目录中的文件列表以便可以处理每个文件?
How do you get a list of files within a directory so each can be processed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
如何获取目录中的文件列表以便可以处理每个文件?
How do you get a list of files within a directory so each can be processed?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(13)
这是我使用的:
Here's what I use:
但是
boost::filesystem
可以做到这一点: http://www.boost.org/doc/libs/1_37_0/libs/filesystem/example/simple_ls.cppBut
boost::filesystem
can do that: http://www.boost.org/doc/libs/1_37_0/libs/filesystem/example/simple_ls.cpp这是 Linux 上 C 语言的示例。 也就是说,如果您使用的是 Linux,并且不介意在 ANSI C 中执行这一小部分操作。
Here's an example in C on Linux. That's if, you're on Linux and don't mind doing this small bit in ANSI C.
C++11/Linux 版本:
C++11/Linux version:
您必须使用操作系统调用(例如Win32 API)或它们的包装器。 我倾向于使用 Boost.Filesystem 作为与混乱的 Win32 API(以及跨平台)相比,它是一个更优秀的接口。
如果您想使用 Win32 API,Microsoft 有一个列表 函数和示例 在 msdn 上。
You have to use operating system calls (e.g. the Win32 API) or a wrapper around them. I tend to use Boost.Filesystem as it is superior interface compared to the mess that is the Win32 API (as well as being cross platform).
If you are looking to use the Win32 API, Microsoft has a list of functions and examples on msdn.
如果您使用的是 Windows 和 使用 MSVC,MSDN 库有执行此操作的示例代码。
并且这是该链接的代码:
If you're in Windows & using MSVC, the MSDN library has sample code that does this.
And here's the code from that link:
我刚刚问了一个类似的问题,这是我基于收到的答案的解决方案(使用
boost::filesystem< /code> 库):
输出如下:
I've just asked a similar question and here's my solution based on answer received (using
boost::filesystem
library):Output is like:
解决这个问题需要特定于平台的解决方案。 在 unix/linux 上查找 opendir() 或在 Windows 上查找 FindFirstFile()。 或者,有许多库可以为您处理特定于平台的部分。
Solving this will require a platform specific solution. Look for opendir() on unix/linux or FindFirstFile() on Windows. Or, there are many libraries that will handle the platform specific part for you.
在结合了很多片段之后,我终于找到了一个可重用的 Windows 解决方案,它使用 ATL 库,它随 Visual Studio 一起提供。
要访问该方法,只需调用:
After combining a lot of snippets, I finally found a reuseable solution for Windows, that uses ATL Library, which comes with Visual Studio.
To access the method, just call:
或者您执行此操作,然后读出 test.txt:
“/b”表示仅返回文件名,没有更多信息。
Or you do this and then read out the test.txt:
The "/b" means just filenames are returned, no further info.
将属性设置为仅查找目录。
Setup the attributes to only look for directories.
您可以使用以下代码获取目录中的所有文件。对 Andreas Bonini 答案进行简单修改以删除“.”的出现。 和 ”..”
You can use the following code for getting all files in a directory.A simple modification in the Andreas Bonini answer to remove the occurance of "." and ".."