Write a C program myfind whose behavior resembles that of the system command fin
ID: 3600218 • Letter: W
Question
Write a C program myfind whose behavior resembles that of the system command find.
myfind accepts the following parameters:
where:
filename is a substring that is matched against each filename in each directory that myfindinspects. If a file name matches filename or if the substring filename occurs within a file name, the name of that file is printed.
startpath is an optional parameter that specifies the directory where myfind must start the search. If this parameter is not specified, myfind starts in the current directory.
For each file whose name is a match, myfind must print its name and its mode.
For each directory in which myfind finds a match, it must print that directory's full path.
Test myfind using various directories on your computer attempting to match full and partial file names. Below is a typical output produced by myfind
NOTE: It is not allowed to use ftw() or any similar library function.
Below is a typical output produced by myfind
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <errno.h>
/* This is just a sample code, modify it to meet your need */
int main()
{
char *filename="sample";
char *folderpath="C:\a";
myFind(filename, folderpath);
return 0;
}
void myFind(char *fileName, char *folderPath)
{
DIR* FD;
struct dirent* in_file;
/* Scanning the in directory */
if (NULL == (FD = opendir (folderPath)))
{
fprintf(stderr, "Error : Failed to open input directory - %s ", strerror(errno));
return 1;
}
while ((in_file = readdir(FD)))
{
if (NULL == (FD = opendir (in_file->d_name)))
{
if (strstr(in_file->d_name, fileName)){
printf("File Name : %s", folderPath + "\" + in_file->d_name);
}
}
else{
myFind(fileName, (folderPath + "\" + in_file->d_name));
}
}
}
Here I have given a recursive function 'myFind()' to print the required file names.
I hard coded the inputs for this function:
char *filename="sample";
char *folderpath="C:\a";
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.