Link to home
Start Free TrialLog in
Avatar of vwWojtek
vwWojtek

asked on

Problems with ls command implemented in C

Hi Experts :)

I wrote a short program to list directory contents.
======================
#include<stdio.h>
#include<sys/types.h>
#include<dirent.h>
#include<stdlib.h>

int main(int argc, char *argv[])
{
int i;
DIR*dp;
struct dirent*dirp;

if (argc==2)
      {
      dp = opendir(argv[1]);
        while ((dirp = readdir(dp)) != NULL)
      printf("%s\n", dirp->d_name);
      }
else
      {
      if (argc == 1)
            {
            dp = opendir("./");
              while ( (dirp = readdir(dp)) != NULL)
                printf("%s\n", dirp->d_name);
            }
      else
            {
            printf("ls - Error - too many parameters\n");
            exit(0);
            }

      };
        closedir(dp);
        return 0;
}
======================
my main problem is, how to format output data - now it is line by line and at random. How to make it look like output of ls in unix ? Second problem is how to handle error if wrong path is given or not existed directory as a parameter ? Thanks in advance for tips how to solve it. Maybe you have an idea how to implement ls -l option to my code ? Thanks :)

cheers
Wojtek
Avatar of Anthony2000
Anthony2000
Flag of United States of America image

Have you studied the source to ls?
If you don't want to, please disregard my post.

http://ftp.gnu.org/gnu/coreutils/

ls is part of coreutils
Avatar of vwWojtek
vwWojtek

ASKER

Hi Anthony, I know it but I want to implement my own, simply version of ls in my simply shell.
ASKER CERTIFIED SOLUTION
Avatar of Infinity08
Infinity08
Flag of Belgium image

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
Have you looked at the  busybox source to ls, I think it is somewhat simpler. Infinity08 has given some good hints. Do you still need help? Do you know C well?
Hi all :)

thanks for answering and usefull advice :)
Your welcome!