扫描 C 语言中的计算机文件



我正在用 C 语言做一个小项目(只是 C 而不是 ++ 或 #),我想知道你们中是否有人知道有一种方法可以扫描文件(只说出它的名称和/或扩展名)?

感谢您提供的任何帮助。

您可以使用以下代码读取文件夹的内容(在以下示例中为当前工作示例),该代码将打印所有文件(和文件夹):

#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
int main (void) {
      DIR *dp;
      struct dirent *ep;
      dp = opendir(".");   // open the current directory
      if (dp != NULL) {
        while ((ep = readdir(dp)) != NULL) {     // read its content one by one
           printf("%sn", ep->d_name);
      }
      closedir(dp);   // close the handle
     }
      else
      perror("Can not access dir");
return 0;
}

当然,您可以在下一步中解析其扩展名的各个文件名。请注意,此示例适用于 Linux。

我在另一个论坛上问了这个问题,几乎马上就得到了很好的答案。

#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
int main (void)
{
    DIR *dp;
    struct dirent *ep;     
    dp = opendir ("./");
    const int MAXFILES = 100;
    char list[MAXFILES][256];
    int c = 0;
if (dp != NULL)
    {
        while ((ep = readdir (dp)) && (c < MAXFILES)){
            strcpy(list[c],ep->d_name);
            ++c;
        }
(void) closedir (dp);
    }
    else
        perror ("Couldn't open the directory");
return 0;
}

最新更新