Friday, 8 May 2015

Simulation Of UNIX Command - LS

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<error.h>
#include<dirent.h>
#include<sys/stat.h>
#include<syslog.h>
#include<unistd.h>
#include<linux/unistd.h>
#define MAX_NO_FILE 40
#define PATH_LEN 200
#define MAXSIZE 100
#define MAXLENGTH 40
char cur_dir[MAXSIZE*4];
char file_list[MAX_NO_FILE][MAXLENGTH];

int listdir(char *dir_path)
{
DIR *dir;
struct dirent* entry;
char entry_path[400+1],back[MAXSIZE];
size_t path_len;
int count=0;
char temp[MAXSIZE*4];
chdir(dir_path);
getcwd(dir_path,MAXSIZE);
getcwd(cur_dir,MAXSIZE);
memset(entry_path,0,sizeof(entry_path));
snprintf(entry_path,400+1,"%s",dir_path);
path_len=strlen(dir_path);


if(entry_path[path_len-1]!='/')
{
entry_path[path_len]='/';
entry_path[path_len+1]='\0';
++path_len;
}
dir=opendir(dir_path);
strcpy(back,dir_path);
strcat(back,"/.../");

while((entry=readdir(dir))!=NULL)
{
strncpy(entry_path+path_len,entry->d_name,sizeof(entry_path)-path_len);
syslog(LOG_INFO,"%s:%s",entry->d_name,entry_path);

if(strcmp(entry->d_name,".")!=0)
{
if(!((entry->d_name[0]=='.')&&(entry->d_name[1]!='.')))
{
if(strcmp(entry->d_name,"..")!=0)
{
snprintf(file_list[count],MAXLENGTH,"%s",entry->d_name);
count++;
if(count>=MAX_NO_FILE)
break;
}
}
}
}
closedir(dir);
return count;
}


int isdir(char *path)
{
char temp[MAXSIZE*4];
struct stat st;
snprintf(temp,MAXSIZE*4,"%s",path);
stat(temp,&st);
if(S_ISDIR(st.st_mode))
return 0;
else
return 1;
}

int main(int argc,char *argv[])
{
int cnt,i;
char path_to_list[PATH_LEN];
if(argc!=2)
printf("usage:myls<path_to_dir>\n");
snprintf(path_to_list,PATH_LEN,"%s",argv[1]);
printf("the files in the directory\n");

if(isdir(path_to_list)==0)
{
cnt=listdir(path_to_list);
for(i=0;i<cnt;i++)
printf("%s\n",file_list[i]);
}
else
printf("%s\n",path_to_list);
return 0;
}



Output:
          
     
[telnet29@linux ~]$ ./a.out /
the files in the directory
misc
boot
opt
mnt
srv
net
lost+found
lib
etc
sbin
proc

tmp

No comments:

Post a Comment