0

I'm recoding the Unix command ls, im using multiple system functions including but not limited to , , functions etc. I have all the information I need and have already taken big strides. However, I need help with formatting the output.

when you run the command ls -l and the output is formatted so all columns are the right size regardless of the length of said files names.

I would like to know how to format my output in the same manner as ls, with regard to columns (Just a general idea not actual code). How do I do this?

10
  • 1
    How would you format it by hand on a piece of paper ? You can also consult the documentation of printf. Commented Jun 9, 2016 at 10:31
  • Go through this [codingunit.com/…. You'll get a good idea how to do that. Commented Jun 9, 2016 at 10:56
  • 1
    In C there are format specifier which can be specified in printf functions. Commented Jun 9, 2016 at 10:59
  • thanks , really helpful. Commented Jun 9, 2016 at 12:03
  • Why are you using the ls command - read up about opendir, readdir etc. and use them instead Commented Jun 9, 2016 at 12:23

1 Answer 1

1

There are various non-printing escape characters that can perform tasks such as moving the cursor to a specific location, changing the font and background colors, etc. You can use them to move the cursor to calculated positions to achieve the neat column-based formatting like the output of the ls command. The characters you would want to consider are the following:

  • \033[l;cH: Moves the cursor to line l and column c.
  • \033[nA: Moves the cursor up n lines.
  • \033[bB: Moves the cursor down n lines.
  • \033[nC: Moves the cursor forward n characters.
  • \033[nD: Moves the cursor backward n characters.
  • \033[2J: Clears the screen and moves the cursor to line 0 and column 0
  • \033[K : Without moving the cursor, clear the line starting from the current cursor position.
  • \033[s : Store the current cursor position
  • \033[u : Move the cursor back to the previously stored location.

For example, the following statement moves the cursor to the the top-left corner of the screen and clears the first line, and returns the cursor back to its original location.

printf("\033[s\033[0;0H\033[K\033[u");

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.