From e1a390dd081a83524e736d565818ae7401fcbbef Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Sat, 12 Nov 2011 13:43:44 -0500 Subject: [PATCH] One more exercise with IO functions. --- ex24_iofunctions06.c | 57 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 ex24_iofunctions06.c diff --git a/ex24_iofunctions06.c b/ex24_iofunctions06.c new file mode 100644 index 0000000..3ae3cc7 --- /dev/null +++ b/ex24_iofunctions06.c @@ -0,0 +1,57 @@ +#include +#include +#include +#include +#include "dbg.h" + + +int main(int argc, char *argv[]) +{ + int fd; + int rc; + long lrc; + char *out; + char buffer[1024]; + fpos_t pos; + FILE *instream; + FILE *outstream; + + check(argc == 2, "You must provide a filename."); + + fd = open(argv[1], O_RDWR | O_CREAT); + check(fd != -1, "Unable to open \"%s\" for reading and writing.", argv[1]); + + rc = fchmod(fd, 0644); + check(rc != -1, "Failed to chmod \"%s\"", argv[1]); + + outstream = fdopen(fd, "w"); + check(outstream != NULL, "Unable to open an outstream."); + + rc = fgetpos(outstream, &pos); + check(rc != -1, "Failed to get position of outstream."); + + rc = fprintf(outstream, "It was written."); + check(rc > 0, "Failed to write to outstream."); + + rc = fflush(outstream); + check(rc != EOF, "Failed to flush outstream."); + + rc = fsetpos(outstream, &pos); + check(rc != -1, "Failed to set outstream back to old position."); + + instream = fdopen(fd, "r"); + check(instream != NULL, "Unable to open an instream."); + + rewind(instream); + lrc = ftell(instream); + check(lrc == 0, "Failed to rewind instream."); + + out = fgets(buffer, 1023, instream); + check(buffer != NULL, "Failed to read from instream."); + + printf("Read this from instream: \"%s\"\n", buffer); + + return 0; +error: + return 1; +}