In: Computer Science
Parse the dirent struct to see if an entry is a directory or a file. If it is a directory, prepend "./" to the filename before printing it out. Include a main that does this below.
Please do the above code using C language.
ANSWER:
I have provided the properly commented
code in both text and image format so you can easily copy the code
as well as check for correct indentation.
Have a nice and healthy day!!
CODE TEXT
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
#include<string.h>
#include <stdio.h>
int main() {
DIR *dir;
struct dirent *ent;
if ((dir = opendir("\\")) == NULL)
perror("opendir() error");
else {
puts("contents of root:");
while ((ent = readdir (dir)) != NULL) {
// condition for file, if . in name but .. not in name and only . not in name
if (strstr(ent->d_name, ".")!=NULL && strstr(ent->d_name, "..")==NULL && strcmp(ent->d_name, ".")!=0)
printf ("File: %s\n", ent->d_name);
else{
// its directory
// defining a prepend string
char prepend[100] = ".\\";
// strcat to prepend it
strcat(prepend,ent->d_name);
// displaying dir
printf ("Folder: %s\n", prepend);
}
}
closedir(dir);
}
}
CODE IMAGE