One more exercise with IO functions.
This commit is contained in:
parent
1789da0d74
commit
e1a390dd08
57
ex24_iofunctions06.c
Normal file
57
ex24_iofunctions06.c
Normal file
@ -0,0 +1,57 @@
|
|||||||
|
#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;
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user