简体   繁体   中英

How to format output to print like Linux Command ls

Im trying to print the names of files and folders in the current directory in columns of equal width similar to the system command ls. The number of columns is based on the width of the terminal window.

I know how to get the terminal dimensions and I already have my file/folder names sorted in an array already. Im not sure how to print them in equal width columns like the example below.

dirA       file2.txt  file5.txt  file8.txt
file0.txt  file3.txt  file6.txt  file9.txt
file1.txt  file4.txt  file7.txt

The format "%s" (of printf() function) has "qualifiers". You are able to ajust a string inside a fixed space:

printf("'%15s'", "abc");
Print: '            abc'

printf("'%-15s'", "abc");
Print: 'abc            '

Using a loop (like for(;;)) you are able to print all elements.

I got the columns to be lined up by messing with the printf width specifier. But if you look at my example I need to print in that order. Im not sure how to set up my loop or loops to do that.

/*example output

directoryA  file2  file5
directoryB  file3  file6
file1       file4  file7

*/


char  *str[] =  {"directoryA", "directoryB", "file1", "file2", file3", "file4", "file5", "file6", "file7" };

int num_files = 9;

int spaceleft = win_width;
int padding = 0;


for(int i = 0; i < num_files; i++)
{

    int space = 1;
    int padding = largest_str - strlen(str[i]);
    int next_string = strlen(str[i]) + space + padding;

    spaceleft = spaceleft - next_string;

    if(spaceleft > next_string)
    {

        printf("%-*s ",largest_str ,str[i]);
    }
    else
    {
        spaceleft = x;
        printf("\n%-*s ",largest_str, str[i]);
        spaceleft = spaceleft - next_string;
    }

}
printf("\n");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM