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
C

Avatar of undefined
Last Comment
Anthony2000

8/22/2022 - Mon
Anthony2000

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
ASKER
vwWojtek

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

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Anthony2000

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?
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
ASKER
vwWojtek

Hi all :)

thanks for answering and usefull advice :)
Anthony2000

Your welcome!