简体   繁体   English

在C printf格式化输出中需要帮助

[英]Need help in C printf formatted output

I am displaying a partition table, and the table is displayed somewhat like: 我正在显示一个分区表,该表显示如下:

Number     Device name       Partition type      Size in MB
------------------------------------------------------------
1           /dev/sda1         NTFS                    300
2           /dev/sda2         *Win95 FAT32             99
3           /dev/sda3         Unknown                 128
4           /dev/sda4         NTFS                  19472
120         /dev/sda120       NTFS                   3000

*=Active partition

Now for displaying the above, we are using formatted output printf and the format string is 现在,用于显示以上内容,我们使用格式化的输出printf,格式字符串为

"%-6d=partition number    %-25.25s=device name  %c=active partition    %-30.30s=part type          %7Ld=size"

Now i want to display the same partition table, but with some slight modification, such that the gaps in partition slots would be displayed by a range, like: 现在,我想显示相同的分区表,但是要进行一些稍微的修改,以使分区槽中的间隙可以按一定范围显示,例如:

5-119     /dev/sda5.../dev/sda119    Empty          0

I am using the formatted string as: 我将格式化的字符串用作:

%d-%-6d=partition range   %s%d...%s%d=(/dev/sda5.../dev/sda119)   %c  %-30.30s  %7Ld

but it does not help me. 但这对我没有帮助。

What should be the correct format string? 正确的格式字符串应该是什么? I am using a gcc compiler. 我正在使用gcc编译器。

I think you need to use snprintf() to prepare the two composite strings, and then a simpler printf() to do the actual printing. 我认为您需要使用snprintf()准备两个复合字符串,然后使用更简单的printf()进行实际打印。 Since you've not shown your actual code, we have to guess at everything, which is a nuisance... 由于您尚未显示实际代码,因此我们必须对所有内容进行猜测,这很麻烦。

int   min = 5;
int   max = 119;
char *dev = "/dev/sda";

char  num_range[32];
char  dev_range[60];

snprintf(num_range, sizeof(num_range), "%d-%d", min, max);
snprintf(dev_range, sizeof(dev_range), "%s%d...%s%d", dev, min, dev, max);

printf("%-10s   %-50.50s   %c%-30.30s  %7d", num_range, dev_range, ' ', "Empty", 0);

You specified %-25.25s for a single device, so it isn't clear whether you should double that for the range, or you should use some other value (or even the same value); 您为单个设备指定了%-25.25s ,因此尚不清楚是否应将该范围的值翻倍,还是应使用其他值(甚至是相同的值); you'll need to tweak that part of the format string to suit yourself. 您需要调整格式字符串的该部分以适合自己。 This technique is also how I get a colon at the end of a name — format the name and the colon into a string, and then format that string into the final print operation. 这种技术也是我在名称末尾得到一个冒号的方法-将名称和冒号格式化为字符串,然后将该字符串格式化为最终的打印操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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