c++ - 在特定条件下迭代文件夹的文件

标签 c++ c string visual-studio-2010 visual-c++

使用 this solution使用 dirent.h,我尝试使用以下代码迭代当前文件夹的特定文件(那些具有 .wav 扩展名 以 3 位数字开头的文件) :

(重要说明:因为我使用 MSVC++ 2010,所以我似乎无法使用 #include <regex>,而且我也无法使用 this,因为不支持 C++11)/p>

DIR *dir;
struct dirent *ent;
if ((dir = opendir (".")) != NULL) {
  while ((ent = readdir (dir)) != NULL) {
    printf ("%s\n", ent->d_name);
    //if substr(ent->d_name, 0, 3) ... // what to do here to 
                                      //  check if those 3 first char are digits?
    // int i = susbtr(ent->d_name, 0, 3).strtoi();        //  error here! how to parse 
                                                         // the 3 first char (digits) as int? 

    // if susbtr(ent->d_name, strlen(ent->d_name)-3) != "wav" // ...

  }
  closedir (dir);
} else {
  perror ("");
  return EXIT_FAILURE;
}

如何使用未完全提供 C+11 支持的 MSVC++2010 执行这些测试?

最佳答案

您实际上不会检查 wav扩展名,只是文件名将以这 3 个字母结尾......

没有substr这样的函数在 C 库中从字符串中提取切片。

您应该检查文件名长度是否至少为 7:strlen(ent->d_name) >= 7 , 然后使用 isdigit 检查前 3 个字符是数字而不是第四个字符来自 <ctype.h> 的函数最后将文件名的最后 4 个字符与 ".wav" 进行比较使用 strcmp或更好strcasecmp .后者可以称为 _stricmp在微软的世界里。如果这些都不可用,请使用 tolower将最后 3 个字符与 'w' 进行比较, 'a''v' .

这里是放宽要求的实现(任意位数):

#include <ctype.h>
#include <stdlib.h>

...

DIR *dir;
struct dirent *ent;
if ((dir = opendir(".")) != NULL) {
    while ((ent = readdir(dir)) != NULL) {
        char *name = ent->d_name;
        size_t length = strlen(name);
        if (length >= 5 &&
            isdigit(name[0]) &&
            name[length-4] == '.' &&
            tolower(name[length-3]) == 'w' &&
            tolower(name[length-2]) == 'a' &&
            tolower(name[length-1]) == 'v') {
               int num = atoi(name);
               printf("%s -> %d\n", name, num);
               /* do your thing */
        }
    }
    closedir(dir);
} else {
    perror ("");
    return EXIT_FAILURE;
}

关于c++ - 在特定条件下迭代文件夹的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28788626/

相关文章:

c++ - 结构、继承和定义

c++ - C++中的事件调度

c++ - 目录迭代器值作为变量

c - 先前的堆栈变量

c - 如何放大 mandelbrot 或 julia 集中的光标位置?

c++ - 从字符串中提取字符

c++ - C++20 范围是否支持按功能分组?

c - 我的 C 程序有一个 char,我希望它能容纳更多数据,我应该用什么数据类型替换它?

c++ - 将 char 数组转换为 WCHAR 数组的最简单方法是什么?

Java字符串操作