Linux 获取屏幕分辨率与窗口行列数(c/c++)

获取当前分辨率

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<sys/mman.h>
#include<sys/ioctl.h>
#include<unistd.h>
#include<fcntl.h>
#include<linux/fb.h>

int main(int argc,char *argv[]){
    int fd;                                                                              
    struct fb_var_screeninfo screen_info;
    fd = open("/dev/fb0",O_RDWR);
    ioctl(fd,FBIOGET_VSCREENINFO,&screen_info);
    printf("%d*%d\n",screen_info.xres,screen_info.yres);
    close(fd);
    return 0;
}

结果:

root@cocktail:~# vim screen_xy.c 
root@cocktail:~# ./screen_xy 
1152*864

获取当前窗口大小

这里大小指的是一个满屏幕的窗口,按照当前字体大小所能显示的字体的行数与列数。
如果调整字体大小,结果会根据字体大小变化。这一结论在ssh工具界面也适用。

#include<stdio.h>
#include<stdlib.h>
#include<sys/ioctl.h>
#include<termios.h>
#include<signal.h>
#include<unistd.h>

int main(int argc,char *argv[]){                                                         
    struct winsize info;
    ioctl(STDIN_FILENO,TIOCGWINSZ,&info);
    printf("当前终端为%d行%d列\n",info.ws_row,info.ws_col);
    return 0;
}

结论:

root@cocktail:~# vim screen_wc.c 
root@cocktail:~# ./screen_wc
当前终端为23行89列

其他

固定行打印进度

#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <signal.h>
#include <unistd.h>
#include <pthread.h>

#define clear() printf("\033[H\033[J")
#define gotoxy(row, col) printf("\033[%dH;%d", (row), (col))
#define moveup(v) printf("\033[%dA", v);
#define movedown(v) printf("\033[XB", v);
#define moveright(v) printf("\033[XC", v);
#define moveleft(v) printf("\033[XD", v);
#define clearscreen() printf("\033[2J");

void progress(int row, int v)
{
    if (v > 100)
        v = 100;

    gotoxy(row, 1);
    fflush(stdout);
    printf("\rIn %d progress %d", row, v);
    fflush(stdout);
}

void showup(int row)
{
    int v1 = 0;
    int v2 = 0;

    while (v1 <= 10000 || v2 <= 10000)
    {
        v1 += rand() % 10;
        v2 += rand() % 5;
        progress(row - 1, v1 / 100);
        progress(row, v2 / 100);

        usleep(1000);
    }
    printf("\n");
}

int main(int argc, char *argv[])
{
    clear();
    showup(10);
    return 0;
}

运行结果如下图:
能够同时在两行打印进度条,当然你想跑一条或者更多条也是可以的

posted @ 2019-02-15 22:06  sinpo828  阅读(1756)  评论(0编辑  收藏  举报