当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/