【问题标题】:How to check how many files are there in a folder?如何查看一个文件夹中有多少个文件?
【发布时间】:2012-01-04 20:03:09
【问题描述】:

我想检查指定目录中有多少文件。例如,我的 .exe 旁边有一个名为 resources 的目录,我想检查其中有多少 .txt 文件。

如何在 Windows 中的 C++ 中做到这一点?

【问题讨论】:

  • 100% 依赖于操作系统。请注意,有些系统是用 C 语言编写的,甚至不存在任何一种 filsystem。如果你在这样的系统上调用 fopen,你会得到链接器错误!
  • 现在标记为 Windows,因此它将是 FindFirstFile()、FindNextFile() 和 FindClose() API 调用。

标签: c++ windows file


【解决方案1】:

我会使用 boost::filesystem。甚至还有一个 sample program 为您完成了大部分工作。

【讨论】:

    【解决方案2】:

    这取决于操作系统。在 Windows 上,您可以使用FindFirstFileFindNextFile 来枚举目录内容,并使用适当的过滤器,例如"*.txt"。完成后不要忘记致电FindClose

    在基于 Unix 的操作系统上,您可以使用 opendir(3)readdir(3) 枚举目录内容。您必须自己过滤文件名。完成后不要忘记致电closedir(3)

    【讨论】:

      【解决方案3】:

      此 MS Windows 代码列出了 C: 中的所有 .txt 文件。要列出所有其他文件,请将 strcpy(DirSpec, "c:\\*.txt") 更改为 strcpy(DirSpec, "c:\\*")

      #include <stdio.h> 
      #include <stdlib.h> 
      #define _WIN32_WINNT 0x0501 
      #include <windows.h> 
      #define BUFSIZE MAX_PATH 
      
      int main(int argc, char *argv[]) 
      { 
          WIN32_FIND_DATA FindFileData; 
          HANDLE hFind = INVALID_HANDLE_VALUE; 
          DWORD dwError; 
          LPSTR DirSpec;
          unsigned int nFiles=0;
          DirSpec = (LPSTR) malloc (BUFSIZE); 
          strcpy(DirSpec, "c:\\*.txt"); 
      
          printf ("Current directory : %s\n\n", DirSpec); 
      
          hFind = FindFirstFile(DirSpec, &FindFileData); 
          if (hFind == INVALID_HANDLE_VALUE) 
          { 
              printf ("incorrect Handle : %u.\n", GetLastError()); 
              return (-1); 
          } 
          else 
          { 
              printf ("%s\n", FindFileData.cFileName); 
      
      
              while ( FindNextFile (hFind, &FindFileData) != 0) 
              { 
                   nFiles++;
                   printf ("%s\n", FindFileData.cFileName); 
              } 
      
              dwError = GetLastError(); 
              FindClose(hFind); 
      
              printf ("\n %d files found.\n\n", nFiles); 
      
              if (dwError != ERROR_NO_MORE_FILES) 
              { 
                   printf ("FindNextFile Error.\n", dwError); 
                   return (-1); 
              } 
          } 
          free(DirSpec); 
         return (0); 
      }
      

      【讨论】:

        猜你喜欢
        • 2018-01-04
        • 2016-02-26
        • 1970-01-01
        • 1970-01-01
        • 2018-08-06
        • 2017-08-28
        • 1970-01-01
        • 2021-05-31
        • 1970-01-01
        相关资源
        最近更新 更多