logoISU  

CS256 - Principles of Structured Design

Fall 2021

Displaying ./code/cs256su21code/jul19/pix.c

/*

This program takes in a file consisting of 10 numbers per line
and makes a picture depending on the binary digits of each number

I wrote this program for a class assignment back in April of 2016,
but I modified it slightly for this class.


*/
#include <stdio.h>
#include <stdlib.h>

#define MSB 7 //most significant bit
#define BITWIDTH 80 // picture is 80 bits wide              

int main(int argc, char *argv[]){

    //prints usage statement if a file isnt provided
    if(argc < 2) {
      fprintf(stderr, "Usage %s <filename>\n", argv[0]);
      exit(1);
     }
  
    //variable declarations
    FILE *fd;  
    int bit, num, bitwidth;
    int bitcount = 0;
  
    //open the file
    fd = fopen(argv[1], "r");
    
    //if fopen returns NULL, print a usage statement and exit
    if(fd == NULL) {
      fprintf(stderr, "Could not open file.\n");
      exit(-1);
   }
     
    //use fscanf to read each integer of the file 
    while (fscanf(fd, "%d", &num) == 1) {

      //for every number, loop through the last 8 binary digits
      //loop from bit 0 to bit 7
       for(int i = 0; i <=MSB; i++){
         bit = num & (1 << i); //AND'ing the number with 1 left shifted i times.
         if(bit != 0) //if the bit isn't 0, print a '#' character
            putchar('#');
         else //else print a space character
            putchar(' ');
        bitcount++;//increment bitcount by 1
       } 
       
       //picture is 80 "bits" wide, so every 80 bits we're printing a newline
       // and resetting the bitcount
       if(bitcount == BITWIDTH){
         printf("\n");
         bitcount = 0;
       }	  
   }
      
  return 0;
  
}