Example of Storing Data in Text and Binary Streams

If two streams are opened, one as a binary stream and the other as a text stream, and the same information is written to both, the contents of the streams may differ. The following example shows two streams of different types and the hexadecimal values of the resulting files.

#include <stdio.h>

int main(void)
{
   FILE *fp1, *fp2;
   char lineBin[15], lineTxt[15];
   int x;
   
   fp1 = fopen("script.bin","wb");
   fprintf(fp1,"hello world\n");
  
   fp2 = fopen("script.txt","w");
   fprintf(fp2,"hello world\n");
  
   fclose(fp1);
   fclose(fp2);

   fp1 = fopen("script.bin","rb");

/* opening the text file as binary to suppress
   the conversion of internal data */
   fp2 = fopen("script.txt","rb");

   fgets(lineBin, 15, fp1);
   fgets(lineTxt, 15, fp2);

   printf("Hex value of binary file = ");
   for (x=0; lineBin[x]; x++)
      printf("%.2x", (int)(lineBin[x]) );

   printf("\nHex value of text file = ");
   for (x=0; lineTxt[x]; x++)
      printf("%.2x", (int)(lineTxt[x]) );

   printf("\n");

   fclose(fp1);
   fclose(fp2);

/* The expected output is:

Hex value of binary file = 68656c6c6f20776f726c640a
Hex value of text file = 68656c6c6f20776f726c640d0a */
}

As the hexadecimal values of the file contents show, in the binary stream script.bin the new-line character is converted to a line feed (\0a). In the text stream script.txt, the new line is converted to a carriage-return line feed (\0d0a).



Stream Processing