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

In this assignment, you are to write a C program – let\'s call it myls.c – that

ID: 3684565 • Letter: I

Question

In this assignment, you are to write a C program – let's call it myls.c – that mimics the ls command. Your program should implement the following ls options:

1.) ls -i option: list the names and i-node numbers of files and directories in the current directory

2.) ls -R option: recursively list the names of all files and directories in the current directory; that is, the command is also applied to the directories within the current directory, the directories within those directories, and so forth

Your program should not use fork/exec, but instead use the actual file system calls themselves:

• opendir() – open a directory

• readdir() – read a directory entry

• closedir() – close a directory

• rewinddir() – reset directory

• getcwd() – get current working directory

• chdir – change current working directory

• stat(), lstat(), fstat() – obtain file information

Explanation / Answer

#include <stdio.h>
#include <dirent.h>
#include <unistd.h>
char *getcwd(char *buf, size_t size);
void lslCommand(){
char dir[1024];
if (getcwd(dir, sizeof(dir)) != NULL){//geting current directory
fprintf(stdout, "Current directory: %s ", dir);
DIR *directory;
directory = opendir(dir);
if(directory!=NULL)
{ //prinitng file name
while((res=readdir(directory))!=NULL)
printf(res->d_name);
}
close(directory);

}
else{
perror("getcwd() error");
}
}

//recursive function
void lsrCoomand (char dir[]){
DIR *directory;
//opening current directory
directory = opendir(dir);
if(directory!=NULL)
{
//reading directory
while((res=readdir(directory))!=NULL){
if (S_ISDIR(res.st_mode)){ //checking if it sub-directory
lsrCoomand(res->d_name)
}
else{ //priting file name
printf(res->d_name);
}
}
}
close(directory);
}
int main(void)
{
//calling functions
lslCommand();
//pssing current directory to function
char dir[1024];
if (getcwd(dir, sizeof(dir)) != NULL){
lsrCoomand(dir);
}
return 0;
}