C语言实现一个ASCII查看器

做了一个ASCII查看的小工具,作为C的练手,也没做优化和封装,代码很硬。

效果如下:

代码如下:

#include <sys/ioctl.h>
#include <stdio.h>
#include <string.h>

int main (void)
{
    struct winsize w;
    ioctl(0, TIOCGWINSZ, & w);
    
    printf("\nASCII tool\nYou can see all ascii code!\ncopy right max2d.com\n\n");
    
    char *head = " \33[33mdec \33[32m| \33[34mhex \33[32m| \33[35mchar ";
    char *head2 = " dec | hex | char ";
    int charslen = (int)strlen(head2);
    int col = w.ws_col / ( charslen + 2);
    
    int glen = col * charslen + (col-1)*2;
    
    for (int q=0; q<glen; q++) {
        printf("\33[32m-");
    }
    printf("\n\33[37m");
    

    for (int t=0; t<col; t++) {
        printf("%s",head);
        if(t<(col-1))
        {
            printf("\33[31m||");
        }
        else
        {
            printf("\n");
        }
    }
    
    for (int t=0; t<col; t++) {
        for(int u=0; u<charslen; u++)
        {
            printf("\33[32m-");
        }
        
        if(t<(col-1))
        {
            printf("\33[31m||");
        }
        else
        {
            printf("\n");
        }
    }
    
    
    int c = 127 - 32 ;
    c = c / col; //差值
    int max = 32 + c;
    for (int i=32; i<max; i++) {
        for (int b=0; b<col; b++) {
            int z = i + b*c;
            if(z<100)
            {
                printf(" \33[33m%d  \33[32m|  \33[34m%x \33[32m|  \33[35m%c   ",z,z,z);
            }
            else
            {
                printf(" \33[33m%d \33[32m|  \33[34m%x \33[32m|  \33[35m%c   ",z,z,z);
            }
            if(b<(col-1))
            {
                printf("\33[31m||");
            }
        }
        printf("\n");
    }
    
    
    for (int q=0; q<glen; q++) {
        printf("\33[32m-");
    }
    printf("\n\33[37m");
    
    return 0;
}