使用 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/