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

i need a c++ program that... Write a (POSIX) program that searches for a specifi

ID: 3716273 • Letter: I

Question

i need a c++ program that...

Write a (POSIX) program that searches for a specified file, and if found,

prints out the relative path of the file from the current working directory and its

time stamp. Your program should take one command line argument, the filename

to find.

If your executable file is “searchFile” and you run this program from the root

directory (“/”) and search for a file named “test.txt”.

To start searching inside the current working directory you need to obtain a pointer

to a DIR structure using the opendir() system call.

Explanation / Answer

void SearchDirectory(string directory, string target_File_Name){
    DIR *dirp = opendir(directory.c_str());
    if (!dirp) {
        perror(("opendir " + directory).c_str());
        return;
    }

    struct dirent *dptr;
    while(dptr = readdir(dirp)){
        string file_Name = dptr->d_name;
        string file_Path = directory + "/" + file_Name;

        struct stat statStruct;
        stat(file_Path.c_str(), &statStruct);
        if( S_ISDIR(statStruct.st_mode) ){
            if ( file_Name.compare(".") == 0 || file_Name.compare("..") == 0 ){
                continue;
            }

            SearchDirectory(file_Path, target_File_Name);
        }
        else if( S_ISREG(statStruct.st_mode)){
            if( file_Name.compare(target_File_Name) == 0){
                cout << file_Path << endl;
            }
        }
    }

    closedir(dirp);
}