【问题标题】:Get each file within a directory in c on Windows获取 Windows 上 c 目录中的每个文件
【发布时间】:2012-10-06 11:58:47
【问题描述】:

我目前正在处理一个 C 项目,我需要扫描一个目录并获取该目录中每个文件的文件名。代码需要在 Windows 和 Linux 上运行。我有使用以下代码的 linux 版本。

DIR *dp;
int i = 0;
struct dirent *ep;
char logPath[FILE_PATH_BUF_LEN];
sprintf(logPath, "%s/logs/", logRotateConfiguration->logFileDir);
printf("Checking pre existing log count in: %s\n", logPath);
dp = opendir(logPath);

if (dp != NULL)
{
    while ((ep = readdir(dp)) != NULL)
    {
        if (strcmp(ep->d_name, ".") != 0 && strcmp(ep->d_name, "..") != 0)
        {
            i = i + 1;
        }
    }
    closedir(dp);
}
else
{
    perror("Couldn't open directory");
}
logRotateConfiguration->logCount = i;

为了使此代码正常工作,我使用了#include <dirent.h>,但发现它与 Windows 不兼容。因此,在我的头文件中,我在 Linux 上使用了 ifdef 来包含 dirent.h,但不确定在 Windows 上可以使用什么。

感谢您提供的任何帮助。

【问题讨论】:

    标签: c windows linux io readdir


    【解决方案1】:

    要在 Windows 上列出文件,您可以使用 FindFirstFile()FindNextFile()。示例见Listing the Files in a Directory

    【讨论】:

    • 我认为 OP 希望在两者上运行通用的东西:The code needs to run on both Windows and Linux
    • @mike,我不这么认为,鉴于问题的标题,并且问题中没有任何内容表明条件预处理器代码包含是不可接受的。
    【解决方案2】:
    【解决方案3】:

    MinGW (link) 有dirent.h。我在网上没有找到关于它具体实现 dirent 的文档,但我认为它与 unix-derivatives 版本足够相似。您可以查看头文件,然后决定是否使用它。

    关于其他答案的注释:我不知道来自 softagalleria.net 的版本,所以我不能谈论它,但关于 FindFirstFile/FindNextFile-API:如果您决定使用它,请确保使用“Unicode” -版本(实际上是 UCS-2),因为 Ascii 版本只允许非常有限的路径长度。要使用 Unicode 版本,请定义宏并确保在所有路径前添加 \\?\

    【讨论】:

      猜你喜欢
      • 2011-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-02
      • 2011-09-11
      • 1970-01-01
      • 2016-08-23
      相关资源
      最近更新 更多