I am very confused. In the while loop I am adding each file name into an array and printing it afterwards.
However in the for loop it prints some weird things and stops executing in the middle.
Please help me to fix it.
char *commands[1000];
char *str;
DIR * dir;
struct dirent * entry;
char *env = getenv("PATH");
do {
str = strsep(&env, ":");
if(str != NULL)
if(strlen(newEnv) > 0) {
dir = opendir(str);
if( dir == NULL ) break;
flag = 0;
while((entry = readdir(dir)) != NULL) {
commands[++count] = entry->d_name;
printf("---%i %s\n", count ,commands[count]); // prints fine
}
closedir(dir); // close directory
}
} while(newEnv);
commands[++count] = '\0';
printf("count = : %i\n", count);
for(int i = 0; i < count; i ++)
{
if(commands[i] == NULL)
break;
printf("aaa%i %s\n\n", i, commands[i]); //problem loop
}
opendir, etc. is probably irrelevant to the problem, so you can probably remove it from your code snippet.strsepon environment variables, since it modifies them. However this is not the source of your problems.newEnvvariable ?newEnv,flag, andcountare not defined.strsep()is not found either but this is maybe because I did not include the proper include file. Which one is it?