使用该解决方案与dirent.h,我想遍历在当前文件夹中的特定文件(那些有.wav
延伸和3个数字开头)用下面的代码:
(重要说明:当我使用MSVC ++ 2010时,似乎无法使用#include <regex>
,并且由于没有C ++ 11支持而无法使用它)
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执行这些测试?
好,这是一个解决方案
#include <stdio.h>
#include <string.h>
int
main(void)
{
const char *strings[] = {"123.wav", "1234 not-good.wav", "456.wav", "789.wav", "12 fail.wav"};
int i;
int number;
for (i = 0 ; i < sizeof(strings) / sizeof(*strings) ; ++i)
{
size_t length;
int count;
const char *pointer;
if ((sscanf(strings[i], "%d%n", &number, &count) != 1) || (count != 3))
continue;
length = strlen(strings[i]);
if (length < 4)
continue;
pointer = strings[i] + length - 4;
if (strncasecmp(pointer, ".wav", 4) != 0)
continue;
printf("%s matches and number is %d\n", strings[i], number);
}
return 0;
}
如您所见,scanf()
检查字符串的开头是否有整数,也跳过所有可能的空格字符,然后捕获被扫描的字符数,如果相等,3
则继续检查扩展名。
如果您使用的是Windows,请替换strncasecmp()
为_strnicmp()
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句