A TEXT file - such as our compiling shell script helper 'goc' - is almost always exclusively printable characters in the terminal window setting.   Strings are ended with one or more 'newline' characters.   Text files contain no font size, font type, bold, italics formatting.  The BINARY file may contain printable characters, but also present are non-printable characters:   control, formatting, etc.   'C' covers both modes of file manipulation - text & binary.   Here we look at the latter.


(right-click to download)

/* pgm20 source */

#include <stdio.h>
#include <stdlib.h>     // random number functions
#include <time.h>       // time functions

#define BINARYFILE    "./binary.dat"
#define SEEDNO          0
#define SEEDYES        1       // POP QUIZ:  how might we convert these 2 '#define' to an 'enum' ?

int get_random_number(int, int);    // returns random number constrained by the 2nd 'int'.  the first 'int' flags to seed or not

int main(void)  {
     int num_bytes_to_write;
     int retval;
     int j;
     FILE *fileptr;

     // 'w+b' = write, binary mode, '+' allows also READING file
     fileptr = fopen(BINARYFILE, "w+b");
     if (fileptr == NULL) {
          printf("\n"); perror("Abort - fopen() to write "); printf("\n");

     // seeding with 'srand()' improves randomness
     num_bytes_to_write = get_random_number(SEEDYES, 35);

     for (j = 0; j < num_bytes_to_write; j++)  {
          retval = fputc(get_random_number(SEEDNO, 256) , fileptr);     // no need to SEED, was done already

          if (retval == EOF) {
               printf("\n");     perror("Abort - fputc() writing ");     printf("\n");

     printf("\nNumber of bytes written to file %s: %d\n\n", BINARYFILE, num_bytes_to_write);
     rewind(fileptr);      // go back to start of file data

     while ((j = fgetc(fileptr)) != EOF)   {
          if (ferror(fileptr))   {
               printf("\n");      perror("Early exit - fgetc() reading ");    printf("\n");
               break; // ... out of nearest enclosing loop
          printf("Dec: %d, Hex: %x, Char: %c\n", j, j, j);


int get_random_number(int flag, int modulo_val)   {
      if (flag == SEEDYES)
     return(rand() % modulo_val);