Bytes To Decimal

Code Id 1
Date Updated 3/7/2010
Title Bytes to decimal  
Description
Write a bytestodecimal program so that
          bytestodecimal f
reads bytes from the file named f and prints each byte as a decimal number,
right-justified (padded with spaces) to four characters. Your program must start a new line
after every 10th byte and at the end of file (if the end of file does not come after a 10th byte).

For example, the output

    84 104 105 115  32 105 115  32  97  32
   116 101 115 116  46  32  84 104 105 115
    32 105 115  32 111 110 108 121  32  97
    32 116 101 115 116  46  10

means that the file contained byte 84 ('T'), byte 104 ('h'), etc. 
                                  
Codes Snippet
#include 
#include 
#include 

void die_read(char *fn)
{
  fprintf(stderr,"bytestodecimal: fatal: unable to read %s: %sn"
    ,fn,strerror(errno));
  exit(111);
}

void die_write(void)
{
  fprintf(stderr,"bytestodecimal: fatal: unable to write output: %sn"
    ,strerror(errno));
  exit(111);
}

int main(int argc,char **argv)
{
  FILE *f;
  int bytes = 0;
  int c;

  if (!argv[1]) {
    fprintf(stderr,"usage: bytestodecimal fn");
    exit(100);
  }

  f = fopen(argv[1],"r");
  if (!f) die_read(argv[1]);

  while ((c = fgetc(f)) != -1) {
    if (printf("%4d",c) == -1) die_write();
    if (++bytes == 10) {
      if (printf("n") == -1) die_write();
      bytes = 0;
    }
  }
  if (ferror(f)) die_read(argv[1]);

  if (bytes)
    if (printf("n") == -1) die_write();

  if (fflush(stdout) == -1) die_write();

  exit(0);
}

Comments are closed.