You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
box-o-sand/lcthw-remnants/ex24_iofunctions06.c

58 lines
1.4 KiB

#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;
}