box-o-sand/oldstuff/lcthw-remnants/ex24_iofunctions06.c
2015-06-22 13:15:42 -05:00

58 lines
1.4 KiB
C

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#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;
}