c - 如何计算 ls 多列显示所需的列宽?

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

当ls显示文件列表时,它根据终端宽度按列显示,我可以知道每列的大小是多少吗?

最佳答案

宽度为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;
}

关于c - 如何计算 ls 多列显示所需的列宽?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53900504/

相关文章:

c - 如何从 c 字符串中读取特定数量的字符?

用于重新排序 XML 元素的 C API?

c - C和Windows API有什么关系?

Python - 哎呀 - 当我有 2.7 时安装了 Python2.6 - 现在默认为 2.6 - 想要 2.7

Linux用户空间和内核空间调度

java - 在android中通过jni调用c中的Main

c - Unix网络编程,协议(protocol)不支持的地址族

linux - Crontab 在 Amazon Linux AMI 2017.09.1 中不工作

android - V4L2:队列满了会发生什么

c - 函数指针的取消引用