Can some on help me out here? I am trying check each directory entry if a letter exists in its name. Obviously it’s not working. My main question is am I using the memchr correctly in using the namelist[n]->d_name as a memory?
#include <dirent.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
int main(void)
{
struct dirent **namelist;
int n;
n = scandir(".", &namelist, 0, alphasort);
if (n < 0)
perror("scandir");
else
{
char * search;
while (n--) {
search= (char*) memchr(namelist[n]->d_name,'a',(sizeof(namelist[n]->d_name)));
if(search !=NULL){
printf("%s\n", namelist[n]->d_name);
free(namelist[n]);
}
char * search;
}
free(namelist);
}
}
That code actually works for me (under Win7/CygWin):
But why are you using
memchr? Thed_namefield is a C-style string, as evidenced by the fact that you can perform aprintf("%s\n",...)on it.You should be using
strchrfor that. Usingmemchrmay search beyond the end of the string, possibly giving false results if it findsain any junk following that.If that doesn’t help you out, then you need to define the phrase “obviously it’s not working”. In other words, what are all the files in the directory and what output are you getting? That will greatly assist in the resoultion of this problem.