aboutsummaryrefslogtreecommitdiff
path: root/ch8/8-02_fopen-and-fillbuf.c
blob: 66d7336932955f8c637ffa4f4789cd3f4ba5d97a (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
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include "syscalls.h"

/* The C Programming Language: 2nd Edition
 *
 * Exercise 8-2: Rewrite `fopen` and `_fillbuf` with fields instead of explicit
 * bit operations. Compare code size and execution speed.
 *
 * Notes: Fields, in this case, are struct fields. I implemented them as 1-bit
 * integers to simulate bit fields via struct.
 *
 * The resulting binary of this file (plus the custom header) runs through this
 * source file in about 0.001s. However, the binary is 1KB larger.
 *
 * Some subsequent exercises use the same syscalls.h file created for this
 * exercise. For this reason, the file only refers to its chapter and not
 * specific exercises.
 */

int main() {
	FILE *fp = fopen("8-02_fopen-and-fillbuf.c", "r");
	if (fp != NULL) {
		puts("We could read the file.\n");
		/* pro tip: don't declare this as 'unsigned' or you'll create an
		 * endless loop thanks to EOF typically being negative. Don't waste
		 * half an hour on a newbie mistake like I did. :)
		 */
		char c;
		while ((c = getc(fp)) != EOF) {
			putchar(c);
		}
		/* fclose calls fflush */
		fclose(fp);
		fclose(stdout);
	} else {
		puts("Could not open file for reading.");
	}
	return 0;
}