gpt4 book ai didi

c - printf() 填充 C 中的列

转载 作者:太空宇宙 更新时间:2023-11-04 06:10:12 24 4
gpt4 key购买 nike

我有一个 C 程序,它正在打印当前目录中文件的详细信息。它是 ls 的更具体版本。我无法让列由一个空格字符分隔。我的功能如下:

    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);

我曾尝试将 %-1s 添加到 printf 语句,但这只会给我一个段错误。如果有人可以帮助我,将不胜感激。谢谢。

我不能只添加空格,因为当您在一列中有文件链接号 > 10 而在下一列中有单个数字链接号时,列将不会对齐。

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

最佳答案

为什么不自己在每个输出后简单地添加一个空格呢?如果您将所有小的 printf 调用组合成一个打印所有内容的调用,那就很容易了:

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);

如果您想要每列的特定宽度,请使用 printf 的字段宽度说明符格式,比如

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);

[请注意,上面的字段宽度只是示例,请试验以获得您想要的宽度]


最后请注意,您永远无法让列在 100% 的时间内对齐,迟早您会得到一些太长以适应您决定的宽度的数据。最好的解决办法是检查它有多普遍,如果普遍就调整宽度,否则就真的没必要费心了。

关于c - printf() 填充 C 中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58627344/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com