Feb 7, 2012

K & R C Programs Exercise 7-2.

K and R C, Solution to Exercise 7-2:
K and R C Programs Exercises provides the solution to all the exercises in the C Programming Language (2nd Edition). You can learn and solve K&R C Programs Exercise.
Write a program that will print arbitrary input in a sensible way. As a minimum, it should print non-graphic characters in octal or hexadecimal according to local custom, and break long text lines. Read more about C Programming Language .
/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                      Happy Coding
***********************************************************/

#include <stdio.h>
#define OCTAL        8
#define HEXADECIMAL 16


void ProcessArgs(int argc, char *argv[], int *output)
{
 int i = 0;
 while(argc > 1)
 {
  --argc;
  if(argv[argc][0] == '-')
  {
   i = 1;
   while(argv[argc][i] != '\0')
   {
    if(argv[argc][i] == 'o')
    {
     *output = OCTAL;
    }
    else if(argv[argc][i] == 'x')
    {
     *output = HEXADECIMAL;
    }

    ++i;
   }
  }
 }
}

int can_print(int ch)
{
 char *printable = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 !\"#%&'()*+,-./:;<=>?[\\]^_{|}~\t\f\v\r\n";

 char *s;
 int found = 0;

 for(s = printable; !found && *s; s++)
 {
  if(*s == ch)
  {
   found = 1;
  }
 }

 return found;
}

int main(int argc, char *argv[])
{
 int split = 80;
 int output = HEXADECIMAL;
 int ch;
 int textrun = 0;
 int binaryrun = 0;
 char *format;
 int width = 0;

 ProcessArgs(argc, argv, &output);

 if(output == HEXADECIMAL)
 {
  format = "%02X ";
  width = 4;
 }
 else
 {
  format = "%3o ";
  width = 4;
 }

 while((ch = getchar()) != EOF)
 {
  if(can_print(ch))
  {
   if(binaryrun > 0)
   {
    putchar('\n');
    binaryrun = 0;
    textrun = 0;
   }
   putchar(ch);
   ++textrun;
   if(ch == '\n')
   {
    textrun = 0;
   }

   if(textrun == split)
   {
    putchar('\n');
    textrun = 0;
   }
  }
  else
  {
   if(textrun > 0 || binaryrun + width >= split)
   {
    printf("\nBinary stream: ");
    textrun = 0;
    binaryrun = 15;
   }
   printf(format, ch);
   binaryrun += width;
  }
 }

 putchar('\n');

 return 0;
}

Read more c programs
C Basic C Strings K and R C Programs Exercise
You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it


(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!
To browse more C Programs visit this link