summaryrefslogtreecommitdiff
path: root/02-10.md
diff options
context:
space:
mode:
authorloshprung <lshprung@scu.edu>2020-02-10 11:11:47 -0800
committerloshprung <lshprung@scu.edu>2020-02-10 11:11:47 -0800
commit89d105f965d422bd15b8c10afd707b4d621ab22a (patch)
treed5b59bd7f9bc7a297436cbc621fb86667b5b2735 /02-10.md
parent685e4c9e8272aa15bf16357ff4a7c79998733d7b (diff)
Post-class 02/10
Diffstat (limited to '02-10.md')
-rw-r--r--02-10.md91
1 files changed, 91 insertions, 0 deletions
diff --git a/02-10.md b/02-10.md
new file mode 100644
index 0000000..9efee8f
--- /dev/null
+++ b/02-10.md
@@ -0,0 +1,91 @@
+[\<- 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
+```