From 11139d2f67e6362fe1ed51d8991ed3bc702b5a15 Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Fri, 11 Nov 2011 08:58:43 -0500 Subject: [PATCH] Adding another io functions exercise for ch25 --- ex24_iofunctions03.c | 59 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 ex24_iofunctions03.c diff --git a/ex24_iofunctions03.c b/ex24_iofunctions03.c new file mode 100644 index 0000000..6413fc4 --- /dev/null +++ b/ex24_iofunctions03.c @@ -0,0 +1,59 @@ +#include +#include "dbg.h" + +#define MAX_FILENAME 2048 + + +int main(int argc, char *argv[]) +{ + int rc = -1; + char *filename; + int nchars = 0; + int nlines = 0; + int i; + long seekpos; + char c; + FILE *fp; + + check(argc > 1, "You must provide a filename as arg 1"); + filename = argv[1]; + + fp = fopen(filename, "r"); + check(fp != NULL, "Failed to open \"%s\".", filename); + + while((c = fgetc(fp)) != EOF) { + nchars++; + if (c == '\n') { + nlines++; + if (nlines % 10 == 0) { + printf("At line %d of \"%s\"\n", nlines, filename); + } + } + } + + printf("\"%s\" contains %d chars\n", filename, nchars); + + printf("Current position of \"%s\" is %ld\n", filename, ftell(fp)); + printf("Writing out \"%s\" in reverse:\n", filename); + + for (i = 0; i < nchars; i++) { + seekpos = (long)nchars - (i + 1); + rc = fseek(fp, seekpos, SEEK_SET); + check(rc != -1, "Failed to seek to %ld", seekpos); + c = fgetc(fp); + check(c != EOF, "Failed to read char at %ld", seekpos); + putc(c, stdout); + } + + rewind(fp); + printf("\n\nRewound \"%s\" to position %ld\n", filename, ftell(fp)); + + rc = fclose(fp); + check(rc != -1, "Failed to close \"%s\".", filename); + + + return 1; + +error: + return 0; +}