Reputation: 769
This code I'm testing gives me a list of files that are in the current working directory.
#include <stddef.h>
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
int main (void)
{
DIR *dp;
struct dirent *ep;
dp = opendir ("./");
if (dp != NULL)
{
while (ep == readdir (dp))
{
puts (ep->d_name);
(void) closedir (dp);
}
}
else
puts ("Couldn't open the directory.");
return 0;
}
The code works, but the compilation with GCC gives me a warning telling me (I use GCC in Spanish) that can happen that the variable ep
may be used without initializing in the function.
I've trying to give the variable ep
a valor to avoid this warning (good practice of programming), but to do it results the program not doing what it's supposed to do.
Any idea what's going on, or what I'm doing wrong?
Upvotes: 1
Views: 335
Reputation: 3324
You are equating an uninitialized variable ep
to return value of a function in this line
while (ep == readdir(dp))
You want assignment
while ((ep = readdir(dp)))
If you want to read all the entries you may want to move closedir()
outside the while
loop
closedir(dp); //no need to cast
Upvotes: 4
Reputation: 10516
puts (ep->d_name); //you are tried access uninitialized pointer
Actually you need to read directory using readdir
, readdir
returns struct dirent *
Now store this return value into ep and need to check readdir
is success or failed.
If an error occurs, NULL is returned and errno is set appropriately.
you need to check ep is NULL or not , but you are check ep == readdir(dp)
while (ep == readdir (dp)) ==> while (ep = readdir (dp))
^^ ^
For clear understanding you can write
while ( (ep == readdir (dp)) !=NULL)
Upvotes: 1
Reputation: 4366
You just need to write
while ((ep = readdir(dp)))
because writing ==
would not assign anything to ep.
The test for the while condition will happen on the result of the expression ep = readdir(dp)
, evaluated to ep final value.
Upvotes: 1