char - Formatting a C Program -


so have program takes file , reads in character character , prints character , hexadecimal equivalent. `

#include <stdio.h> #include <stdlib.h>  int main(){ file *labfile; char buf;  labfile = fopen("lab1.dat", "r"); if (labfile == null) perror("error opening file\n");     while( (buf = fgetc(labfile) ) != eof){         if(("%x", buf)< 16){             printf("%c 0%x\n", buf, buf);         }         else             printf("%c %x\n", buf, buf);    }    fclose(labfile);    return 0; } 

` program works way need except 1 thing. need program output hex number on top character directly underneath number , process needs continue horizontally.

any appreciated!

you should output characters hex first, , save each read in character has been printed until run out of columns on screen. can move next line, , print out characters saved underneath hex output.

you can simplify logic format hex output single print statement.

when printing out character, need have plan represent non-printable characters. in sample program below, handle printing 2 consecutive dots.

void print_chars (unsigned char *p, int num) {    int i;    (i = 0; < num; ++i) {       printf("%s%c%s",              isprint(p[i]) ? " "  : ".",              isprint(p[i]) ? p[i] : '.',              (i < num-1) ? " " : "\n");    } }  int main() {    file *labfile;    char buf;    int count = 0;    int num = columns/3;    char printed[num];    labfile = fopen("lab1.dat", "r");    if (labfile == null) perror("error opening file\n");    while( (buf = fgetc(labfile) ) != eof) {       printf("%s%02x", count ? " " : "", buf);       printed[count++] = buf;       if (count == num) {          count = 0;          putchar('\n');          print_chars(printed, num);       }    }    fclose(labfile);    if (count) {       putchar('\n');       print_chars(printed, count);    }    return 0; } 

the number of columns divided 3 since each character takes 3 columns output (2 hex characters, , space). retrieving number of columns system dependent, can plug in 80 if wish.


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -