【问题标题】:how to compute the required column width for the ls multi-columns display?如何计算 ls 多列显示所需的列宽?
【发布时间】:2019-05-22 20:29:38
【问题描述】:

ls显示文件列表时,会根据终端宽度分列显示,请问每列的大小是多少?

【问题讨论】:

  • 您是在询问如何重现 ls 输出(使用 column)或如何从 ls 输出中获取列大小?
  • @KamilCuk 例如,如果终端的宽度是 167 列(我通过使用 iotctl 得到它,w.ws_col),ls /dev 显示 5 列中的文件列表,但如果调整大小终端到 89 列 ls 在 2 列中显示相同的 ls /dev 文件列表,我想知道 ls 如何确定要在终端中显示的列数?
  • 获取所有文件名;找出哪个是最长的,看看它会进入控制台宽度的次数。
  • ls 是 Linux 中 Coreutils 的一部分。 coreutils "ls" source code filetype:c
  • @rici 在“sh”列中是 8 个空格选项卡的倍数,我可以这样做来重现两个显示吗?

标签: c linux linux-kernel linux-device-driver ls


【解决方案1】:

宽度为 W,输出 N 个文件。您可以进行二分搜索以找到最大列数。

您可以假设 1 列总是可能的(每行一个文件),而 N 列是不可能的(从技术上讲,当所有内容都可以打印在一行上时,只是为了可视化二进制搜索适用)。

示例代码:

#include <stdio.h>

#define N 12 // Number of files
#define W 80 // Terminal width

int can_be_printed(int *lengths, int columns)
{
    int lines = 1 + (N-1) / columns; // ceil(N / columns)
    for(int i=0; i<lines; i++)
    {
        int w = 0; // For the required line width
        w += lengths[i]; // First column
        for(int j=i+lines; j<N; j+=lines) // For each filename in the same line
            w += 2 + lengths[j]; // 2 is the space between filenames for the output
        if(w > W) // Required width is higher than terminal width
            return 0; // false
    }
    return 1; // true
}

int main()
{
    int file_lengths[N] = {7, 9, 9, 5, 6, 8, 9, 6, 7, 13, 6, 10};
    int low = 1; // Always possible
    int high = N; // Generally, not possible
    while(high - low > 1) // Perform binary search
    {
        int mid = (low + high)/2; // Cut in half
        int ans = can_be_printed(file_lengths, mid); // true or false
        if(ans) // If it's possible with the width mid
            low = mid;
        else
            high = mid;
    }
    int ans;
    if(can_be_printed(file_lengths, high)) // End BS picking the highest that is possible
        ans = high;
    else
        ans = low;
    printf("Maximum number of columns: %d\n", ans);
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-15
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-22
    相关资源
    最近更新 更多