Playing with binary read/write
This commit is contained in:
parent
7241713b3f
commit
ac113056a8
1
lcthw/.ex17play.argv
Normal file
1
lcthw/.ex17play.argv
Normal file
@ -0,0 +1 @@
|
||||
ex17play.bin
|
38
lcthw/ex17play.c
Normal file
38
lcthw/ex17play.c
Normal 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;
|
||||
}
|
Loading…
Reference in New Issue
Block a user