Skip to content

Instantly share code, notes, and snippets.

@aagontuk
Created June 17, 2016 10:15
Show Gist options
  • Save aagontuk/1a66e15efb0bcdb51c05ba834f229ff2 to your computer and use it in GitHub Desktop.
Save aagontuk/1a66e15efb0bcdb51c05ba834f229ff2 to your computer and use it in GitHub Desktop.
My Unix ls command clone attempt
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <time.h>
#include <string.h>
char filetype(struct stat *fs);
int main(int argc, char *argv[]){
DIR *dirp;
struct dirent *sd;
struct stat fs;
char real_path[PATH_MAX + 1];
if((dirp = opendir(argv[1])) == NULL){
perror("opendir");
exit(1);
}
errno = 0;
while((sd = readdir(dirp)) != NULL){
/* resolving absolute path */
strcpy(real_path, "");
if(strcmp(argv[1], ".") != 0){
strcat(real_path, argv[1]);
strcat(real_path, sd->d_name);
}
else{
strcpy(real_path, sd->d_name);
}
if(stat(real_path, &fs) == -1){
perror("stat");
exit(3);
}
/* print filetype and permission */
printf("%c%c%c%c%c%c%c%c%c%c\t", filetype(&fs),
(fs.st_mode & S_IRUSR) ? 'r' : '-',
(fs.st_mode & S_IWUSR) ? 'w' : '-',
(fs.st_mode & S_IXUSR) ? 'x' : '-',
(fs.st_mode & S_IRGRP) ? 'r' : '-',
(fs.st_mode & S_IWGRP) ? 'w' : '-',
(fs.st_mode & S_IXGRP) ? 'x' : '-',
(fs.st_mode & S_IROTH) ? 'r' : '-',
(fs.st_mode & S_IWOTH) ? 'w' : '-',
(fs.st_mode & S_IXOTH) ? 'x' : '-'
);
/* print UID & GID */
printf("%d\t%d\t", (fs.st_mode & S_ISUID), (fs.st_mode & S_ISGID));
/* print size */
printf("%ld\t", (long)fs.st_size);
/* print last modification time */
printf("%.24s\t", ctime(&fs.st_mtim.tv_sec));
printf("%s\n", sd->d_name);
}
if(sd == NULL && errno){
perror("readdir");
exit(2);
}
return 0;
}
char filetype(struct stat *fs){
char ch;
switch(fs->st_mode & S_IFMT){
case S_IFSOCK:
ch = 's';
break;
case S_IFLNK:
ch = 'l';
break;
case S_IFIFO:
ch = 'p';
break;
case S_IFREG:
ch = '-';
break;
case S_IFBLK:
ch = 'b';
break;
case S_IFDIR:
ch = 'd';
break;
case S_IFCHR:
ch = 'c';
break;
default:
ch = '?';
}
return ch;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment