Reputation: 1153
I am trying to implement the ls program using the dirent library. It appears that my DIR * mydir is of <unspecified type>
when I debug with gdb, which says to me that it's as if I am not correctly including the dirent.h header, but I believe that I am correctly including all the required header files.
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
//Specifies whether or not to print hidden files
#define PRINT_HIDDEN 0
void readDirectory(char *dirString[]);
int main(int argc,char* argv[])
{
if(argc!=2)
{
printf("Usage: ./ls <directory>\n");
}
readDirectory(argv);
return 0;
}
void readDirectory(char *dirString[])
{
DIR *mydir;
struct dirent *entry;
//Opening the directory and checking if valid
mydir = opendir(dirString[1]);
if(mydir==NULL){
fprintf(stderr,"ls: cannot access %s: No such file or directory\n",
dirString);
exit(EXIT_FAILURE);
}
//Printing directories/files in specified directory
while((entry==readdir(mydir))!=NULL);
{
if(PRINT_HIDDEN)
{
printf("%s ",entry->d_name);
}
else
{
if(entry->d_name[0]!='.')
{
printf("%s ",entry->d_name);
}
}
}
printf("\n");
//Closing the directory
closedir(mydir);
}
Upvotes: 0
Views: 3082
Reputation: 145287
Well hidden in badly presented code lie two ugly bugs:
while((entry==readdir(mydir))!=NULL);
{
...
}
Use this instead:
while ((entry = readdir(mydir)) != NULL) {
...
}
entry
is uninitialized, compiling with warnings enabled as by gcc -Wall
would have spotted the problem. The extra ;
at the end of the while
condition is harder to spot, use a more consistent programming style to avoid such mistakes.
Upvotes: 6