/* bitstreams.cpp A demonstration of writing individual bits to a file, and reading individual bits from a file. S. Tanimoto, Oct. 18, 1999. */ #include /* These static ints are used to buffer the input and output and to keep a count of the number of bits read and written. */ static int currentByte = 0; static int numBitsUsedInByte = 0; static int totalNumBitsWritten = 0; static int totalNumBitsRead = 0; /* Take a string like "00101" and write it to the output file. Since we can only really write 8 bits at a time, we have to buffer up the bits until 8 bits are ready, and then write out that byte. Any character other than 1 or NULL is written out as 0. */ void writeBits(char *bitString, FILE *filePointer) { while (*bitString != NULL) { char thisDigit = *bitString++; currentByte <<= 1; /* shift left one place */ if (thisDigit == '1') currentByte++; /* Insert new bit */ numBitsUsedInByte++; totalNumBitsWritten++; /* If we have 8 good bits, write them out */ if (numBitsUsedInByte == 8) { putc((char)currentByte, filePointer); currentByte = 0; numBitsUsedInByte = 0; } } } /* print the remaining bits in a full byte by themselves. */ void flushBits(FILE *filePointer) { currentByte <<= (8 - numBitsUsedInByte); putc((char)currentByte, filePointer); currentByte = 0; numBitsUsedInByte = 0; } /* Gets the next bit from the input stream and returns it as an int. If it has to read a new byte, but cannot because end-of-file is reached, it returns -1. */ int readOneBit(FILE *filePointer) { int temp = 0; int bit = 0; if (numBitsUsedInByte == 0) { currentByte = getc(filePointer); if (currentByte == EOF) return -1; } temp = currentByte & 0x80; /* access bit 7 */ currentByte &= 0x7F; /* mask off bit 7 */ currentByte <<= 1; /* shif remaining bits left */ numBitsUsedInByte++; numBitsUsedInByte = numBitsUsedInByte % 8; totalNumBitsRead++; if (temp > 0) bit = 1; return bit; } /* Write out some bits to one file. Then read in some bits from another file. */ int main() { FILE *infile, *outfile; int bit; outfile = fopen("outBits.dat", "w"); writeBits("1010101010101", outfile); writeBits("111", outfile); writeBits("001", outfile); flushBits(outfile); fclose(outfile); printf("Total number of bits written to the stream is %d.\n", totalNumBitsWritten); /* Now let's read the bits back in. */ infile = fopen("inBits.dat", "rb"); if (infile == NULL) { printf("Could not open the file for reading.\n"); exit (0); } printf("Here are the bits read back in: \n"); while ( (bit = readOneBit(infile)) != -1) { printf("%d", bit); } fclose(infile); printf("\n"); printf("Total number of bits read from the stream is %d.\n", totalNumBitsRead); exit (0); }