#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2005
    Posts
    243
    Rep Power
    17

    Formatting text output to a command line


    Hey,

    I am playing around with a C application and I am trying to figure out how to format text output to the command line. My scenario is that I have lists of files/directories and I want to format them in the same fashion as 'ls' does to list its files and directories - neatly formatted into columns, unless a filename exceeds the width of the terminal window in which case it puts each entry on a separate line.

    I tried tabbing the entries to line them up but due to the random filename lengths I got mixed results. If anyone could give me a hint on how to go about doing this I would appreciate it!

    Thanks for your time.
  2. #2
  3. Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Jun 2005
    Posts
    5,964
    Rep Power
    4852
    Tabs are not the answer. Many systems will interpret a tab as being 8 spaces. Others may have other values.

    Read about printf. Read carefully.

    Exercise your code with pencil and paper. How did that work out?

    I'm sure you have seen presentations that work very well, thus, you know that it's not impossible. Thinking time will be well repaid, though it seems to be a non-starter for many.
    Write no code whose complexity leaves you wondering what the hell you did.
    Politically Incorrect DaWei on Pointers Grumpy on Exceptions
  4. #3
  5. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,244
    Rep Power
    2222
    You should also get a listing of the output of ls that you want to emulate. Save it as a text file (redirecting the output should do the trick, I'd think). That way, you'll be able to measure field widths and determine which column each field starts in.

    Then you will be able to apply what your research had taught you about printf's format string.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2005
    Posts
    243
    Rep Power
    17
    Thanks for the pointers - I managed to get the formatting I was after using:

    Code:
      struct ttysize ts;
      ioctl( 0, TIOCGSIZE, &ts );
    
      int colWidth = maxStrLen + PADDING;
      int numCols = ts.ts_cols / colWidth;
    
      int i;
      for( i = 0; i < size; i++ )
        {
          printf( "%-*s", colWidth, entries[i].out );
    
          if( i % numCols - 1 == 0 || i == size - 1 )
    	printf( "\n" );
        }
    Cheers!

IMN logo majestic logo threadwatch logo seochat tools logo