I'm making a program where I need to check if files in the directory are correct (46 files and all 11 chars).
I've got two methods to do it but I don't know which one is better.
Using opendir/readdir:
int checkfiles()
{
DIR *dir;
struct dirent *dp;
int count = 0;
if ((dir = opendir("img/")) != NULL)
{
while ((dp = readdir(dir)) != NULL)
if (dp->d_name[0] != '.')
{
count++;
if (strlen(dp->d_name) != 11)
error(4);
}
if (count != 46)
error(3);
if (closedir(dir) == -1)
error(2);
}
else
error(1);
return (0);
}
or using scandir:
int checkfiles()
{
struct dirent **namelist;
int i = 0;
int n;
n = scandir("img/", &namelist, 0, alphasort);
if (n < 0)
error(1);
else if (n != 48)
error(3);
else
{
while (i++ < n - 1)
{
if (namelist[i]->d_name[0] == '.')
continue;
if (strlen(namelist[i]->d_name) != 11)
error(4);
free(namelist[i]);
}
free(namelist);
}
return (0);
}
The second is more readable with less indentation, but uses more resources by sorting all files.