February 17th, 2009, 06:16 PM
Formatting text output to a command line
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.
February 17th, 2009, 07:05 PM
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.
February 17th, 2009, 07:23 PM
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.
February 18th, 2009, 08:19 AM
Thanks for the pointers - I managed to get the formatting I was after using:
struct ttysize ts;
ioctl( 0, TIOCGSIZE, &ts );
int colWidth = maxStrLen + PADDING;
int numCols = ts.ts_cols / colWidth;
for( i = 0; i < size; i++ )
printf( "%-*s", colWidth, entries[i].out );
if( i % numCols - 1 == 0 || i == size - 1 )
printf( "\n" );