最终的结果是将目录中文件的扩展名与2个单独的数组字符串进行比较,以便我可以对其进行排序并将其放到2个不同的文件夹中。
我在比较两个不同数组的字符串..esp与2个不同大小的字符串数组时遇到问题。
任何建议表示赞赏。
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>
int main (void)
{
DIR *dirP;
struct dirent *dp;
char *fileN; int i = 0;
char *extMov[]= {".mp4",".flv"};
char *extMusic[]= {".mp3"};
dirP = opendir ("/Users/abc/Downloads");
if (dirP != NULL)
{
while ((dp = readdir(dirP)) != NULL)
{
if((fileN = strrchr(dp->d_name,'.')) != NULL)
{
for (i=0; extMov[i] != NULL; i++)
{
if(strcmp (fileN,extMov[i]) == 0)
{
printf("%s\n",dp->d_name);
}
}
}
}
closedir(dirP);
}
else
perror (" Could not open the directory\n");
return 0;
}
您遇到的最大问题是,数组通常不会以任何方式终止。所以在你的循环中
for (i=0; extMov[i] != NULL; i++)
您很可能会跳出界线,并继续进行迭代,直到内存中有NULL
某个地方,而这可能会超出界限。超出范围访问数组会导致未定义的行为,并使整个程序都怀疑有错误和违法行为,即使它可以正常编译且没有警告。
要解决此问题,您可以使用一些技巧来计算数组中的数字条目:
for (i=0; i < sizeof(extMov) / sizeof(extMov[0]); i++)
但是请注意,此技巧仅适用于适当的阵列。您必须记住,数组经常会衰减为指针,例如,将数组作为参数传递给函数时,此技巧将不起作用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句