Link to home
Start Free TrialLog in
Avatar of stivharding
stivharding

asked on

Emulating the unix LS command in C

Done most of the hard work, that is written most of it its just little errors that im having trouble with. I can't get it working within  the bash shell (linux) when trying to test it. If anyone could give me any pointers on where im going wrong be much grateful. (def.h holds other stuff needed for other emulated commands)

CODE FOR LS PLUS ITS HEADER FILE I"VE WRITTEN

#include "def.h"

int main ()
{
 
  DIR *dirp;
  struct stat sbuf;
  struct passwd *pass;
  struct group *grp;                       /* Define variables */
  struct dirent *direntp;
  char *cwd;
  char time[256];
  char flag[MAXNAME+1];
  flag[0]='\0';
 
  while(*lineptr==' ' || *lineptr == '\t')   /* Remove leading white space */
    ++lineptr;
  getname(flag);                           /* Call getname function */
  cwd = getcwd(NULL, 64);                  /* Get current working directory */
  if(cwd != '\0')
    {
      if ((dirp = opendir(cwd)) != NULL)     /* open current working dir */
      {
        while ((direntp = readdir(dirp)) != NULL)  /* Read all filenames */
          {
            stat(direntp->d_name, &sbuf);
            if(flag[0]=='-' && (flag[1]=='l' || flag[2]=='l')) {
            
            
            pass = getpwuid(sbuf.st_uid);  /* Get info for pwuid */
            
            
            grp = getgrgid(sbuf.st_gid);   /* Get group info */
            
            /* prints all the permissions for the files */
            
            /* if((sbuf.st_mode & S_IFDIR)==S_IFDIR) printf("d"); else printf("-"); */
            if((sbuf.st_mode & S_IRUSR)==S_IRUSR) printf("r"); else printf("-");
            if((sbuf.st_mode & S_IWUSR)==S_IWUSR) printf("w"); else printf("-");
            if((sbuf.st_mode & S_IXUSR)==S_IXUSR) printf("x"); else printf("-");
            if((sbuf.st_mode & S_IRGRP)==S_IRGRP) printf("r"); else printf("-");
            if((sbuf.st_mode & S_IWGRP)==S_IWGRP) printf("w"); else printf("-");
            if((sbuf.st_mode & S_IXGRP)==S_IXGRP) printf("x"); else printf("-");
            if((sbuf.st_mode & S_IROTH)==S_IROTH) printf("r"); else printf("-");
            if((sbuf.st_mode & S_IWOTH)==S_IWOTH) printf("w"); else printf("-");
            if((sbuf.st_mode & S_IXOTH)==S_IXOTH) printf("x"); else printf("-");
            
            
        /* Prints out user name and group */
            printf("%5d %-8s %-8s ", sbuf.st_nlink, pass->pw_name, grp->gr_name);
            
            /* Prints size of file */
            printf("%-7d", sbuf.st_size);
            /* Creates string */
            strcpy(time, ctime(&(sbuf.st_mtime)));
            time[16] = '\0';
            
            /* Prints time */
            printf(&time[4]);
            printf("  ");
            printf("%s\n", direntp->d_name);
            }
            
            /* Checks arguments */
            if(flag[0]=='-' && flag[1]=='a' && flag[2]!='l'){
            printf("%s  ", direntp->d_name);
            } else {
            
            if(*direntp->d_name != '.' && (flag[1]!='l' && flag[2]!='l'))
              printf("%s  ", direntp->d_name);  /* Print file name */
            }
          }
        closedir(dirp);
        printf("\n");
      } else
        printf("%s: Can't open %s\n", cwd);
    } else
      printf("Usage: %s filename\n", cwd);
 
  return 0;                                /* Return to main program */
} /* end shls */


heres def.h

#include <stdio.h>
#include <limits.h>
#include <signal.h>
#include <fcntl.h>
#include <dirent.h>
#include <time.h>
#include <pwd.h>
#include <grp.h>
/* #include <locale> */
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>    /* header file included to remove forkexec warning*/
#include <unistd.h>       /* header file included to remove forkexec warning*/
#include <sys/wait.h>     /* header file for declaration of wait*/
#include <ctype.h>
#include <string.h>
#include <sys/param.h>

#define TRUE 1
#define FALSE 0
#define OKAY 1
#define ERROR 0
#define MAXLINE 200                  /* Maximum length of input line */
#define MAXARG 20      /* Max number of args for each simple command */
#define PIPELINE 5    /* Max number of simple commands in a pipeline */
#define MAXNAME 100    /* Maximum length of i/o redirection filename */

char line[MAXLINE+1];                        /* User typed input line */
char *lineptr;                  /* Pointer to current position in line[] */
char avline[MAXLINE+1];               /* Argv strings taken from line[] */
char *avptr;                /* Pointer to current position in avline[] */
char infile[MAXNAME+1];                   /* Input redirection filename */
char outfile[MAXNAME+1];             /* Ouput redirection filename */
char pathname[MAXPATHLEN];

int backgnd;                   /* TRUE if & ends pipeline else FALSE */
int lastpid;               /* PID of last simple command in pipeline */
int append;            /* TRUE for append redirection (») else FALSE */

struct cmd
{
  char *av[MAXARG];
  int infd;
  int outfd;
} cmdlin[PIPELINE];          /* Argvs and fds, one per simple command */
/*
int main (void);*/            /*Prototypes to tell the compiler the return*/                  
void initcold (void);      /*type of the specified function, the prototypes*/
void initwarm (void);      /*also tell the compiler the number and type of the*/
int getline (void);            /*function's parameters*/
int parse (void);
void execute (int j);
void forkexec(struct cmd *ptr);
int check(char *ptr);
void command (int i);
void getname(char *name);
int convertSignal (char *sSig);
int getwd();
int builtInCommands();
int shcd();
int shpwd();
int shkill();
int shls();
int shps();
int argCount();
ASKER CERTIFIED SOLUTION
Avatar of nebeker
nebeker

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of nebeker
nebeker

A few more things I should point out:

1.  The getname(flag) function was commented out because you didn't define it in the code you posted...  Since that function is supposed to set the value of "flag", your code will always run in (ls) mode.  I had to manually set flag to be "-l" (and recompile) to get it to work in (ls -l) mode.

2.  The first line of your code (the 'while()' loop) will always cause crash because you're trying to dereference a pointer that isn't pointing to anything!   Seems to me that you missed the step where to have 'lineptr' point to something meaningful.

3.  Your main() declaration is wrong.  Since you aren't accepting any parameters, how do you expect to be able to set the -l flag?  Your main should look like this:

int main( int argc, char **argv )

Then you can look at the parameters passed in through argv[1] and find out if you should use the -l or -la mode...
There are two other things you need to look at as well.  First of all, you aren't freeing the memory returned by the getcwd() function.  This will cause a memory leak in your code.  You can fix this easily, though:

change:

  if ((dirp = opendir(cwd)) != NULL)

to:

  dirp = opendir( cwd );
  free( cwd );

  if( dirp != NULL )
  ...


Second, your listing is including the "." and ".." entries whenever the -l flag is set.  These should only be printed when "-al" flags are being used...
Avatar of sunnycoder
No comment has been added lately and this question is therefore classified abandoned.

If asker wishes to close the question, then refer to
https://www.experts-exchange.com/help/closing.jsp

Otherwise, I will leave a recommendation in the Cleanup topic area that this question is:
PAQed with A grade to nebeker

Please leave any comments here within the next seven days. It is assumed that any participant not responding to this request is no longer interested in its final disposition.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

Sunny
EE Cleanup Volunteer
Hi. If anyone can help me with ls –l  I appreciate that. I've written program in c to stimulate ls -l.
 it's works well except the link. I need to print out the line like this
 lrwxrwxrwx 1 admin admin 11 Feb 27 19:08 figC.18 -> ipc/fifo1.c.  
 but it’s just print   lrwxrwxrwx 1 admin admin 11 Feb 27 19:08 figC.18.  I need to make my program print the link also.
Thanks for your help