如何使用填充正确格式化 printf()? [英] How to format printf() correctly with padding?
问题描述
我正在重新创建 unix shell 命令,目前正在执行 ls.我必须模仿 ls -l 来显示权限、文件大小等.本机 ls -l 如果格式正确,则每一列都保持对齐,如下所示:
I am re-creating the unix shell commands and am currently doing ls. I have to mimic ls -l which shows permissions, file size, ect. The native ls -l if formatted well so every column stays aligned like this:
-rw-r--r-- 1 matt matt 1474560 Apr 11 14:54 diskimage
drwxr-xr-x 2 matt matt 4096 Mar 25 15:31 Example
-rwxr-xr-x 1 matt matt 26375 Apr 12 14:24 final
-rwxr-xr-x 1 matt matt 75 Apr 11 14:39 log.sh
现在,我的 ls 版本做了几乎相同的事情,除了当 printf() 函数中使用不同的值时我的列不会对齐,如下所示:
Right now, my version of ls does almost the same thing, except my columns do not line up when different values are used in the printf() function like this:
drwxr-xr-x 0 1024 Dec 03 14:11 .
drwxr-xr-x 0 1024 Dec 03 14:11 ..
drwxr-xr-x 0 1024 Dec 03 13:57 Z
drwxr-xr-x 0 1024 Dec 03 14:11 X
drwxr-xr-x 0 1024 Dec 03 13:56 Y
-rw-r--r-- 0 334632 Dec 10 08:39 big
如您所见,最后一个条目未对齐,因为大小列比其余条目大.如何告诉 printf 函数以自动对齐列的格式化方式打印?
As you can see, the last entry is not aligned because the size column is bigger than the rest. How can I tell the printf function to print in a formatted way with automatically aligned columns?
推荐答案
方法如下:
printf("%8d", 334632);
d
转换说明符之前的数字告诉 printf()
用空格填充打印的数字,以便它(至少)在屏幕上占据(至少)8 个字符.你可以在那里写任何整数.您案例的完整格式字符串可能类似于:
The number before the d
conversion specifier tells printf()
to pad the printed number with whitespace so that it occupies (at least) for example, 8 characters on screen. You can write any integer number there. A complete format string for your case might be something like:
"%9s\t%4d\t%8d\t%16s\n"
如果您想要可变数量的填充:
If you want a variable amount of padding:
printf("%*d\n", max_field_width, 42);
这篇关于如何使用填充正确格式化 printf()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!