I have this function that uses readdir(). I use stat() to get info about the files that are in the directory I give as parameter.
folder_name[] is actually the absolute path for the directory I want to read
The function works fine for names like .
or ./lfac
but it doesn't work properly for names like ./lfac/comp
. I test it and it reads some files from that directory but not all of them. The executable file is placed in the root directory.
I have another function (recursive function) which also uses readdir() and stores a list with the absolute paths of the files that are in the directory (I give as parameter) and its subdirectories. This function has the same problem.
void content(char folder_name[], char *answer)
{
DIR *diropen;
struct dirent *dirread;
if ((diropen = opendir(folder_name)) == NULL)
{
printf ("Error opening directory %s\n",folder_name);
exit(EXIT_FAILURE);
}
while ((dirread = readdir (diropen)) != NULL)
{
struct stat sb;
memset(&sb, 0, sizeof sb);
char *temp;
temp = (char*) malloc (sizeof(char));
temp[0] = 0;
sprintf(temp,"%s/%s",folder_name,dirread->d_name);
if(strcmp(dirread->d_name,".")==0 || strcmp(dirread->d_name,".")==0)
continue;
if (stat(temp, &sb) == -1) {
perror("stat");
exit(EXIT_FAILURE);
}
strcat(answer,"File name: ");
strcat(answer,dirread->d_name);
strcat(answer,"\n");
strcat(answer,"File type: ");
switch (sb.st_mode & S_IFMT) {
case S_IFBLK: strcat(answer,"block device\n"); break;
case S_IFCHR: strcat(answer,"character device\n"); break;
case S_IFDIR: strcat(answer,"directory\n"); break;
case S_IFIFO: strcat(answer,"FIFO/pipe\n"); break;
case S_IFLNK: strcat(answer,"symlink\n"); break;
case S_IFREG: strcat(answer,"regular file\n"); break;
case S_IFSOCK: strcat(answer,"socket\n"); break;
default: strcat(answer,"unknown?\n"); break;
}
sprintf(temp,"I-node number: %ld\n", (long) sb.st_ino); strcat(answer,temp);
.......
}
}