Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //--------------------------------------------
- // NAME:Konstantin Georgiev
- // CLASS:XIa
- // NUMBER:15
- // PROBLEM:#1
- // FILE NAME:m.c
- // FILE PURPOSE: ls unix function implementation in C
- //---------------------------------------------
- #include<stdio.h>
- #include<dirent.h>
- #include<stdlib.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <unistd.h>
- #include <string.h>
- //--------------------------------------------
- // FUNCTION: printNormalContents
- // prints a directory's contents
- // PARAMETERS:
- // char *thing - The name of the directory to be opened
- // int hidden - a flag that tells the function if it needs to display hidden files
- // int isDirectory - a flag that tells the function if it needs to print the directory name
- //--------------------------------------------
- void printNormalContents(char *thing, int hidden, int isDirectory){
- if(isDirectory != 1){
- printf("\n%s:\n", thing);
- }
- DIR*p;
- struct dirent *d;
- p = opendir(thing);
- if(p == NULL){
- fprintf(stderr, "ls: cannot access %s: No such file or directory", thing);
- return;
- }
- while(d=readdir(p)){
- if(d->d_name[0] != '.' || hidden == 1){
- struct stat path_stat;
- stat(d->d_name, &path_stat);
- if(S_ISREG(path_stat.st_mode)){
- printf("- %s\n",d->d_name);}
- else if(S_ISDIR(path_stat.st_mode)){
- printf("d %s\n",d->d_name);}
- else if(S_ISCHR(path_stat.st_mode)){
- printf("c %s\n",d->d_name);}
- else if(S_ISBLK(path_stat.st_mode)){
- printf("b %s\n",d->d_name);}
- else if(S_ISFIFO(path_stat.st_mode)){
- printf("p %s\n",d->d_name);}
- else if(S_ISLNK(path_stat.st_mode)){
- printf("l %s\n",d->d_name);}
- else if(S_ISSOCK(path_stat.st_mode)){
- printf("s %s\n",d->d_name);}
- }
- }
- }
- int main(int argc, char **argv){
- int hidden = 0;
- int flag = 0;
- int dirFlag = 0;
- if(argc > 1){
- if(argc == 2){dirFlag = 1;}
- if(argv[1][0] == '.'){printNormalContents("./", hidden, 1);
- return;}
- for(int i = 1; i < argc; i++){
- if(strstr(argv[i], "-") != NULL && (strstr(argv[i], "a") != NULL || strstr(argv[i], "A") != NULL) ){hidden = 1;}
- }
- for(int i = 1; i < argc; i++){
- if(strstr(argv[i], "-") == NULL){
- if(strstr(argv[i], "/") == NULL){
- if(strstr(argv[i], ".") != NULL && argv[i][0] != '.'){
- if(access(argv[i], F_OK) != -1){
- printf("- %s\n", argv[i]);}
- else{
- fprintf(stderr, "ls: cannot access %s: No such file or directory", argv[i]);}
- }
- else{
- printNormalContents(argv[i], hidden, dirFlag);}}
- else{printNormalContents(argv[i], hidden, dirFlag);}
- flag = 1;
- }
- }
- if(flag == 0){printNormalContents("./", hidden, 1);}
- }
- else{
- printNormalContents("./", hidden, 1);}
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement