1

End game was to compare the extensions of files in the directory to 2 separate string of arrays to that i could sort it and put it 2 different folders..

I am having a problem comparing the strings of two different arrays.. esp with 2 different sized string arrays..

any suggestions is appreciated..

#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>

int main (void)
{
 DIR *dirP;
 struct dirent *dp;
 char *fileN; int i = 0;
 char *extMov[]= {".mp4",".flv"};
 char *extMusic[]= {".mp3"};

 dirP = opendir ("/Users/abc/Downloads");
 if (dirP != NULL)
 {
  while ((dp = readdir(dirP)) != NULL)
  {
   if((fileN = strrchr(dp->d_name,'.')) != NULL)
   {
    for (i=0; extMov[i] != NULL; i++)
    {
     if(strcmp (fileN,extMov[i]) == 0)
     {
      printf("%s\n",dp->d_name);
     }
    }
   }
  }
  closedir(dirP);
 }
 else
  perror (" Could not open the directory\n");
 return 0;
}

2 Answers 2

1

The big problem you have is that arrays are not normally terminated in any way. So in your loop

for (i=0; extMov[i] != NULL; i++)

you will most likely step out of bounds, and continue iterating untill there is a NULL somewhere in memory, which might be quite far out of bounds. Accessing an array out of bounds leads to undefined behavior and makes your whole program suspect of errors and illegalities, even though it might compile fine and without warnings.


To solve this problem you can use a little trick to calculate the number entries in an array:

for (i=0; i < sizeof(extMov) / sizeof(extMov[0]); i++)

Do note however that this trick only works on proper arrays. You have to remember that arrays often decays to pointer, for example when passing an array as argument to a function, and then this trick will not work.

Sign up to request clarification or add additional context in comments.

2 Comments

this idea definitely works.. but is there a way to compare 2 arrays in this case , extMov and extMusic in a single pass(of for loop)? the problem i face is both arrays will be of different so i will need 2 for loops to do the job...
If the size of the array are not the same yes using two for loops will be the best choice.
1

your for loop is looking for a NULL value to stop, but you didn't set a NULL value to your array.
So this extMov[i] != NULL might never be found (depending on the content of your memory)

char *extMov[]= {".mp4",".flv", NULL};

I explicitly add a NULL as the last entry of my array to be sure to have it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.