Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Assitance in wiritng the following program in the C Programming language without

ID: 3715419 • Letter: A

Question

Assitance in wiritng the following program in the C Programming language without using the system function:

In this assignment, you are writing a program to

i) Search all subdirectories that have the name specified by the user. The search should be conducted recursively from the parent directory that the user also specifies.

ii) Whenever each subdirectory with the same name is found in the recursive search, the list of the files in the subdirectory is displayed to the console screen along with the file attributes shown in the following: " All the attributes associated file that are displayed when you run "ls -l filename"

Your program should accept two parameters as shown in the following: % dirSearchList subDirNameToBeFound parentDirectoryFromWhichSearchShouldBegin

Suppose that you want to search all subdirectories that has the name "fork" and the recursive search begins from /home/ADILSTU/kwsuh/. The following command should be used: % dirSearchList fork /home/ADILSTU/kwsuh

The following shows the result of a sample run (Note that I had two subdirectories called "fork" and each of the subdirectories contains a few regular files.) % dirSearchList fork /home/ADILSTU/kwsuh

The following shows the result of another sample run (Note that I don’t have any subdirectory called “dirdoesnotexist”.

   % dirSearchList dirdoesnotexist /home/ADILSTU/kwsuh

    SEARCH FAILED!!

Explanation / Answer


1down voteaccepted

I've just tested the following code and it appears to work correctly:

public static List<File> findDirectoriesWithSameName(String name, File root) {

List<File> result = new ArrayList<>();

for (File file : root.listFiles()) {

    if (file.isDirectory()) {

      if (file.getName().equals(name)) {

        result.add(file);

      }

      result.addAll(findDirectoriesWithSameName(name, file));

    }

}

return result;

}

Your original code was almost there, you just omitted the part where you actually add matching directories to your result list.

Tested with:

C: mp oo

C: mp ooar

C: mp ooaz

C: mp ooaz oo

C: mp ooaz ooar

Using

public static void main(String[] args) throws Exception {

List<File> files = findDirectoriesWithSameName("foo", new File("C:\tmp"));

for (File f :files) {

    System.out.println(f);

}   

}

Output:

C: mp oo

C: mp ooaz oo

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote