Login
Order Now
Support
C Programming Task to Display The Contents Of Files Both As Raw Bytes And As Characters

C Programming Task to Display The Contents Of Files Both As Raw Bytes And As Characters

  • 6th Apr, 2022
  • 17:24 PM

#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>

char a[100000] = {0};
long int size = 0;

/* prints a line of 10 bytes (max) in hex with a space between each byte */
void print_bytes_hex(unsigned char *b, unsigned int nbytes)
{
    /* Your code goes here */
    printf("  ");
    int i = 0;
    for(; i < nbytes; i++){
        printf("%02X ", b[i]);
    }
    while(nbytes++ < 10){
        printf("   ");
    }
}


/* prints a line of 10 bytes (max) in as characters.
 * non-printable bytes are printed as the period character. */
void print_bytes_char(unsigned char *b, unsigned int nbytes)
{
    /* Your code goes here */
    printf(" ");
    for(int i=0; i < nbytes; i++){
        if(isprint(b[i]))
            printf("%c", b[i]);
        else
            printf(".");
    }
}


int main()
{
    /* Your code goes here */
    FILE *fp;
    fp=fopen("logo.txt","rb");  // read+binary mode
    //fp=fopen("logo.txt","rb");  // read+binary mode
    fseek(fp, 0, SEEK_END);
    size = ftell(fp);  // size of file in bytes
    fseek(fp, 0, SEEK_SET);  // same as rewind(fp)
    for(int i=0; i<size; i++){
        fread(&a[i], sizeof(char), 1, fp);  // read one char at a time
    }
    fclose(fp);
    
    printf("Offset              Bytes              Characters\n");
    printf("------  -----------------------------  ----------\n");

    /* Your code goes here */
    int i = 0;
    size--;
    unsigned char b[10];
    while(i < size){
        printf("%6d", i);
        int j = 0;
        for(; j < 10 && i < size; j++){
            b[j] = a[i];
            i++;
        }
        print_bytes_hex(b, j);
        print_bytes_char(b, j);
        printf("\n");
    }

    return 0;
}
 

Share this post

assignment helpassignment helperassignment expertsassignment writing services