ILE C/C++ Programmer's Guide


Storing Data as a Text Stream or as a Binary Stream

If two streams are opened, one as a binary stream and the other as text stream, and the same information is written to both, the contents of the stream may differ. The following illustrates two streams of different types. The hexadecimal values of the resulting files (which show how the data is actually stored) are not the same.

Figure 107. Comparison of Text Stream and Binary Stream Contents




/* Use CRTBNDC SYSIFCOPT(*IFSIO) */
#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 = 888593939640a69699938425 */
/* Hex value of text file = 888593939640a6969993840d25 */
}

As the hexadecimal values of the file contents shows in the binary stream (script.bin), the new-line character is converted to a line-feed hexadecimal value (0x25). While in the text stream (script.txt), the new-line is converted to a carriage-return line-feed hexadecimal value (0x0d25).


[ Top of Page | Previous Page | Next Page | Table of Contents ]