计算目录中具有给定扩展名的文件数量 - C++?
在 C++ 中是否可以计算目录中具有给定扩展名的文件的数量?
我正在编写一个程序,最好做这样的事情(伪代码):
if (file_extension == ".foo")
num_files++;
for (int i = 0; i < num_files; i++)
// do something
显然,这个程序要复杂得多,但这应该让您大致了解我正在尝试做什么。
如果这是不可能的,请告诉我。
谢谢!
Is it possible in c++ to count the number of files with a given extension in a directory?
I'm writing a program where it would be nice to do something like this (pseudo-code):
if (file_extension == ".foo")
num_files++;
for (int i = 0; i < num_files; i++)
// do something
Obviously, this program is much more complex, but this should give you the general idea of what I'm trying to do.
If this is not possible, just tell me.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
C 或 C++ 标准本身没有任何关于目录处理的内容,但几乎任何有价值的操作系统都会有这样的野兽,一个例子是 findfirst/findnext 函数或
readdir
。您执行此操作的方法是对这些函数进行简单的循环,检查为您想要的扩展返回的字符串的末尾。
类似于:
如上所述,您将用于遍历目录的实际函数是特定于操作系统的。
对于 UNIX,几乎肯定会使用 opendir,readdir 和 closedir。这段代码是一个很好的起点:
There is nothing in the C or C++ standards themselves about directory handling but just about any OS worth its salt will have such a beast, one example being the
findfirst/findnext
functions orreaddir
.The way you would do it is a simple loop over those functions, checking the end of the strings returned for the extension you want.
Something like:
As stated, the actual functions you will use for traversing the directory are OS-specific.
For UNIX, it would almost certainly be the use of opendir, readdir and closedir. This code is a good starting point for that:
这种功能是特定于操作系统的,因此没有标准的、可移植的方法来执行此操作。
但是,使用 Boost 的文件系统库,您可以以可移植的方式执行此操作以及更多与文件系统相关的操作。
This kind of functionality is OS-specific, therefore there is no standard, portable method of doing this.
However, using Boost's Filesystem library you can do this, and much more file system related operations in a portable manner.
首先,您要为什么操作系统编写?
FindFirstFile
和FindNextFile
。man
中的opendir
和readdir
或readdir_r
。First of all what OS are you writing for?
FindFirstFile
andFindNextFile
in MSDN.man
foropendir
andreaddir
orreaddir_r
.