函数:
#include <stdio.h>
#include <dirent.h>
#include <string.h>
char *getPhotoName(int num)
{
int i = 0;
int filesize = 0;
DIR *dir = NULL;
struct dirent *entry;
char *photoDir="../resource/photo/";
static char photoPath[50]; //用static
if((dir = opendir(photoDir))==NULL)
{
printf("opendir failed!");
return 0;
}
else
{
while(entry=readdir(dir))
{
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0 )
continue;
i++;
if(num==i)
{
bzero(photoPath,50);
strcat(photoPath, photoDir);
strcat(photoPath, entry->d_name);
//printf("filename%d = %s\n",i,entry->d_name); //输出文件名
closedir(dir);
//printf("%s\n",photoPath);
return photoPath;
}
}
closedir(dir);
}
return 0;
}
调试:
int main(){
printf("%s\n",getPhotoName(3));
printf("%s\n",getPhotoName(2));
return 0;
}
结果: