Playing with binary read/write

This commit is contained in:
Dan Buch 2024-05-03 22:37:15 -04:00
parent 7241713b3f
commit ac113056a8
Signed by: meatballhat
GPG Key ID: A12F782281063434
2 changed files with 39 additions and 0 deletions

1
lcthw/.ex17play.argv Normal file
View File

@ -0,0 +1 @@
ex17play.bin

38
lcthw/ex17play.c Normal file
View File

@ -0,0 +1,38 @@
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if (argc < 2) {
errx(EXIT_FAILURE, "Missing filename argument\n");
}
int init = 0;
FILE *fp = fopen(argv[1], "r+");
if (!fp) {
fp = fopen(argv[1], "w+");
init = 1;
}
if (!fp) {
err(EXIT_FAILURE, "Failed to open file\n");
}
int counter = 0;
if (!init) {
fread(&counter, sizeof(int), 1, fp);
}
counter++;
rewind(fp);
size_t wrote = fwrite(&counter, sizeof(int), 1, fp);
fprintf(stderr, "Wrote %d (%lu bytes)\n", counter, wrote);
fclose(fp);
return 0;
}