Lab 2 - Working with Directory Structures
1.) Write a C program to emulate the ls -l UNIX command that prints all files in a current directory
and lists access privileges, etc. DO NOT simply exec ls -l from the program.
#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include<dirent.h>
int main()
DIR * dp;
struct dirent * entry;
struct stat statbuf;
if((dp = opendir(".")) == NULL)
printf("Cannot open directory \n");
return 0;
chdir(".");
while((entry = readdir(dp)) != NULL)
lstat(entry->d_name,&statbuf);
if(!S_ISDIR(statbuf.st_mode))
{
printf("%s \t \t",entry->d_name);
printf((S_ISDIR(statbuf.st_mode)) ? "d" : "-");
printf((statbuf.st_mode & S_IRUSR) ? "r" : "-");
printf((statbuf.st_mode & S_IWUSR) ? "w" : "-");
printf((statbuf.st_mode & S_IXUSR) ? "x" : "-");
printf((statbuf.st_mode & S_IRGRP) ? "r" : "-");
printf((statbuf.st_mode & S_IWGRP) ? "w" : "-");
printf((statbuf.st_mode & S_IXGRP) ? "x" : "-");
printf((statbuf.st_mode & S_IROTH) ? "r" : "-");
printf((statbuf.st_mode & S_IWOTH) ? "w" : "-");
printf((statbuf.st_mode & S_IXOTH) ? "x" : "-");
printf("\n\n");
Output
2.) Write a program that will list all files in a current directory and all files in subsequent
subdirectories.
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
void printdir(char *dir, int depth)
DIR *dp;
struct dirent *entry;
struct stat statbuf;
if((dp = opendir(dir)) == NULL)
fprintf(stderr,"cannot open directory: %s\n",dir);
return;
chdir(dir);
while((entry = readdir(dp)) != NULL)
lstat(entry->d_name,&statbuf);
if(S_ISDIR(statbuf.st_mode))
/* Found a directory,
but ignore . and .. */
if(strcmp(".",entry->d_name) == 0 ||strcmp("..",entry->d_name) == 0)
continue;
printf("%*s%s/\n",depth,"",entry->d_name);
/* Recurse at a new
indent level */
printdir(entry->d_name, depth+4);
else { printf("%*s%s\n",depth,"",entry->d_name); }
chdir("..");
closedir(dp);
int main()
printf("Directory scanof current one:\n");
printdir(".",0);
printf("Done.\n");
exit(0);
Output
3.) How do you list all installed programs in Linux?
dpkg –l OR apt list
4.) How do you find out what RPM packages are installed on Linux?