【问题标题】:Methods to iterate every file in a directory (in C on Windows)?迭代目录中每个文件的方法(在 Windows 上的 C 中)?
【发布时间】:2019-04-16 17:39:48
【问题描述】:

我一直在寻找可以监视目录以进行文件创建/修改等的方法。但是我发现的所有以前的 Windows 帖子都是 C++ 特定的。

Microsoft 确实列出了ReadDirectoryChangesW,但这也适用于 C++(我不知道这些是否与 C 兼容)。我只知道 Linux 的 inotify 知识,这相当简单,并且想知道是否有任何与 Windows 等效的简单示例? (我不想在 Windows 上使用 inotify,尽管它在技术上是可以实现的)。

【问题讨论】:

  • ReadDirectoryChangesW 不适用于 C++。它可以由 C 代码直接调用,绝大多数标准 WinAPI 函数也是如此。有一个使用 Delphi(绝对不是 C++)here 的示例,几乎可以直接翻译成 C。
  • @dbush:这个问题与措辞不佳的标题不符。发帖人正在寻找 ReadDirectoryChangesW,

标签: c windows loops


【解决方案1】:

如果您只是在寻找方法,也许这会有所帮助: https://www.geeksforgeeks.org/c-program-list-files-sub-directories-directory/ (只是复制粘贴代码以防万一)

在 linux 机器上测试过,它似乎可以工作。虽然不是递归的。

int main(void) 
{ 
        struct dirent *de; /* Pointer for directory entry */

        /* opendir() returns a pointer of DIR type. */ 
        DIR *dr = opendir("."); 

        if (dr == NULL) /* opendir returns NULL if couldn't open directory */
        { 
                printf("Could not open current directory" ); 
                return 0; 
        } 

        /* Refer http://pubs.opengroup.org/onlinepubs/7990989775/xsh/readdir.html 
          for readdir() */
        while ((de = readdir(dr)) != NULL) 
                        printf("%s\n", de->d_name); 

        closedir(dr);    
        return 0; 
}

此外,如果您需要检查列出的文件是否为目录,请参阅此问题: Checking if a dir. entry returned by readdir is a directory, link or file

这种方法可能不像看起来那么便携,但值得一试。

干杯!

【讨论】:

  • 我认为 OP 要求的是 Windows 本机解决方案,而不是 POSIX。
猜你喜欢
  • 2012-10-06
  • 2019-07-08
  • 1970-01-01
  • 1970-01-01
  • 2011-08-03
  • 1970-01-01
  • 2018-09-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多