aboutsummaryrefslogtreecommitdiff
path: root/ch8/8-02_stdlib-fopen-and-fillbuf.c
diff options
context:
space:
mode:
authorzlg <zlg@zlg.space>2018-12-22 01:23:35 -0800
committerzlg <zlg@zlg.space>2018-12-22 01:23:35 -0800
commit4ad4e6c7f6d2fb414d22dd3e55801c85b02c1af7 (patch)
tree91b550a1399eaaf5643341893d98a6526bca86cb /ch8/8-02_stdlib-fopen-and-fillbuf.c
parentAUTHORS: update contact info (diff)
downloadknr-4ad4e6c7f6d2fb414d22dd3e55801c85b02c1af7.tar.gz
knr-4ad4e6c7f6d2fb414d22dd3e55801c85b02c1af7.tar.bz2
knr-4ad4e6c7f6d2fb414d22dd3e55801c85b02c1af7.tar.xz
knr-4ad4e6c7f6d2fb414d22dd3e55801c85b02c1af7.zip
Solve Exercise 8-2: fopen and fillbuf
Diffstat (limited to 'ch8/8-02_stdlib-fopen-and-fillbuf.c')
-rw-r--r--ch8/8-02_stdlib-fopen-and-fillbuf.c33
1 files changed, 33 insertions, 0 deletions
diff --git a/ch8/8-02_stdlib-fopen-and-fillbuf.c b/ch8/8-02_stdlib-fopen-and-fillbuf.c
new file mode 100644
index 0000000..2219757
--- /dev/null
+++ b/ch8/8-02_stdlib-fopen-and-fillbuf.c
@@ -0,0 +1,33 @@
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.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: This file uses the standard library exclusively, in contrast to the
+ * partial replacement solution in the other 8-02 files.
+ *
+ * The resulting binary of this file executes in about 0.001s, just like the
+ * partial replacement solution. Its binary is 1KB smaller, however.
+ */
+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);
+ }
+ } else {
+ puts("Could not open file for reading.");
+ }
+ return 0;
+}