[\<- Notes 02/07](02-07.md) --- # Files Continued ## Binary Files - Use Binary Files when no need for a human to read the file - Converting information into a stream of characters and back into internal format (in this case) is wasting computational cycles and time - Files containing binary numbers that are the computer's internal representation of each file component - Created by executing a program that stores directly in the computer's internal representation of each file component - Actually just a stream of zeros and ones and cannot be read with a text editor - Example `char x = 2` in memory is `00000010` - Example `short x = 2` in memory is `0000000000000010` - Example `int x = 2` in memory is `00000000000000000000000000000010` - To open a binary file for reading: ``` FILE *infp; if((infp = fopen("data.txt", "rb")) == NULL) printf("cannot open the file data.txt\n"); ``` - The file is always open for reading from the beginning - The file name can also be stored in a string - To read from a binary file: ``` ret = fread(&x, sizeof(int), 1, infp); ``` - The file is read sequentially - Consecutive calls to fread will read consecutive elements from the file - The next integer is placed into the variable x - Function fread returns the number of elements read - At the end of the file, fread returns -1 - To open a binary file for writing from the beginning: ``` FILE *outfp; if((outfp = fopen("data.txt", "wb")) == NULL) printf("cannot open the file data.txt\n") ``` - To open a binary file for writing from the end (append): ``` FILE *outfp; if((outfp = fopen("data.txt", "ab")) == NULL) printf("cannot open the file data.txt\n") ``` - To write to a binary file: ``` ret = fwrite(&x, sizeof(int), 1, outfp); ``` - The contents of variable x is written to the file - The file is written sequentially - function fwrite returns the number of elements written - To close a binary file: ``` fclose(infp); fclose(outfp); ``` - **Files cannot be written or read unless specifically set to do so** - cannot read when open to write and vice versa - must close the file if currently open for reading before opening for writing and vice versa List of Functions to Learn/Remember: ``` fopen, fclose fprintf, fscanf fgets fread, fwrite fpurge fflush fseek ```