Luk*_*keN 14
如果不排除基本上始终可用的C标准库,则可以使用该标准库.因为无论如何它都可以使用,与boost不同,它是一个非常实用的选项!
这里给出一个例子.
和这里:
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
int main (void)
{
DIR *dp;
int i = 0;
struct dirent *ep;
dp = opendir ("./");
if (dp != NULL)
{
while (ep = readdir (dp))
i++;
(void) closedir (dp);
}
else
perror ("Couldn't open the directory");
printf("There's %d files in the current directory.\n", i);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
果然
> $ ls -a | wc -l
138
> $ ./count
There's 138 files in the current directory.
Run Code Online (Sandbox Code Playgroud)
这根本不是C++,但它可以在大多数(如果不是全部)操作系统上使用,并且无论如何都可以在C++中使用.
更新:我将更正我之前关于这是C标准库的一部分的陈述 - 事实并非如此.但是你可以将这个概念带到其他操作系统,因为它们都有自己处理文件的方式,而不必占用额外的库.
Yac*_*oby 10
你不能.你能得到的最接近的是使用像Boost.Filesystem这样的东西
小智 6
一个老问题,但由于它首先出现在谷歌搜索上,我想添加我的答案,因为我需要类似的东西.
int findNumberOfFilesInDirectory(std::string& path)
{
int counter = 0;
WIN32_FIND_DATA ffd;
HANDLE hFind = INVALID_HANDLE_VALUE;
// Start iterating over the files in the path directory.
hFind = ::FindFirstFileA (path.c_str(), &ffd);
if (hFind != INVALID_HANDLE_VALUE)
{
do // Managed to locate and create an handle to that folder.
{
counter++;
} while (::FindNextFile(hFind, &ffd) == TRUE);
::FindClose(hFind);
} else {
printf("Failed to find path: %s", path.c_str());
}
return counter;
}
Run Code Online (Sandbox Code Playgroud)
小智 5
从 C++17 开始,它可以用 STL 来完成:
auto dirIter = std::filesystem::directory_iterator("directory_path");
int fileCount = std::count_if(
begin(dirIter),
end(dirIter),
[](auto& entry) { return entry.is_regular_file(); }
);
Run Code Online (Sandbox Code Playgroud)
一个简单的 for 循环也有效:
auto dirIter = std::filesystem::directory_iterator("directory_path");
int fileCount = 0;
for (auto& entry : dirIter)
{
if (entry.is_regular_file())
{
++fileCount;
}
}
Run Code Online (Sandbox Code Playgroud)
请参阅https://en.cppreference.com/w/cpp/filesystem/directory_iterator
| 归档时间: |
|
| 查看次数: |
34023 次 |
| 最近记录: |