summaryrefslogtreecommitdiff
path: root/02-10.md
blob: 9efee8f03aba449585de67f0b8ccefa9a6d02ffa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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
```