简体   繁体   中英

printf() Padding for columns in C

I have a C program that is printing the details of files in the current directory. It is a more specific version of ls. I am having trouble getting the columns to be separated by one space character. My function is as follows:

    while ( (sd = readdir(dir)) != NULL) {
    lstat(sd->d_name, &sfile);

    printf("%hu", sfile.st_mode);

    printf("%d", sfile.st_nlink);

    pwd = getpwuid(sfile.st_uid);
    printf("%s", pwd->pw_name);

    grp = getgrgid(sfile.st_gid);
    printf("%s", grp->gr_name);

    printf("%lld", sfile.st_size);

    t = sfile.st_mtime;
    tmp = localtime(&t);
    strftime(MY_TIME, sizeof(MY_TIME), "%Y-%m-%d %H:%M", tmp);
    printf("%s", MY_TIME);

    printf("%s\n", sd->d_name);

I have tried adding %-1s to the printf statements but that only gives me a seg fault. If anyone can help me that would be greatly appreciated. Thank you.

I cannot just add spaces because the columns will not be aligned when you have, for example, file link number > 10 in one column and a single digit link number in the next.

Current output:
16877  5  bobmichaels  staff  160  2019-10-30 09:54
16832  23  bobmichaels  staff  736  2019-10-29 22:24

Desired output:
16877  5   bobmichaels  staff  160  2019-10-30 09:54
16832  23  bobmichaels  staff  736  2019-10-29 22:24

Why not simply add a space after each output yourself? Very easy if you combine all the small printf calls into a single call that prints all:

printf("%hu %d %s %s %lld %s %s\n",
       sfile.st_mode, sfile.st_nlink, pwd->pw_name, grp->gr_name, sfile.st_size, MY_TIME, sd->d_name);

If you want specific widths of each column, use the field-width specifier of the printf format, like

printf("%-4hu %-5d %10s %10s %lld %10s %s\n",
       sfile.st_mode, sfile.st_nlink, pwd->pw_name, grp->gr_name, sfile.st_size, MY_TIME, sd->d_name);

[Note that the field widths above are just examples , experiment to get the widths you want]


Lastly note that you can never gett columns to align 100% of the time, sooner or later you will get some data that is to long to fit in the width you decided. The best solution is to check how common it is, and if it's common then adjust the widths, but otherwise there's really no need to bother.

If I understood it right, why not just put the space in the printf, something like:

printf(" %s");

if you want to print a column length 10 with right justify:

printf("%10s");

if you want to print a column with length 10 left justify:

printf("%-10s");

columns will be padded with whites spaces, if the column is bigger than 10 will push other columns.

if u want them to be separated by space just add space after "%lld " or in front of next one if u want all be justify add \t

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