We help IT Professionals succeed at work.

Searching for a file

razvanl
razvanl asked
on
Medium Priority
253 Views
Last Modified: 2010-04-21
Hi,

I'm making a C++ program and I need to search for a file in several directories.  Now we can assume I have a list of directories in an array and I know what file I'm looking for (that would be nice).  Now, I need to know which directory -- if any -- the file is in.  I'd appreciate any help.

Sincerely,
Razvan L.
Comment
Watch Question

Commented:
If you have a list of directories to search amd you have the name of the file to be found surely its just a matter of stepping through the array, using the directory from each element of the array in conjunction with the filename to generate a full path for the filename and then fstat the file along the following lines....

for(i=0;i<number_of_elements_in_the_array;i++)
{
  sprintf(sz_fullpath,"%s/%s",directories[i],sz_file);
  if(fstat(sz_fullpath,&stat)==0)
      break;
}
printf("The file was found in %s\n",directories[i]);

Note that you don't need access rights to the files to fstat them but you do need rights to access the directory so the app may need to run setuid.

If however you have a list of base directories and you want to recurse through sub-directories from each of these you can use the ftw() api which recurses through subdirectories from a base directory and runs a user specified function from within each directory found. You could adapt the above code to achieve the same results in this case.

Cheers - Gavin

Author

Commented:
Hi,

Thanks for the answer.  I've already found a way to do it via the opendir() and readdir() functions  but I'm always happy to find another way of doing it.  I'm not sure which is better -- I do have to go through all the files with readdir() to find the one I want.. still it does work.

Sincerely,
Razvan L.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.