Solution for Exercise 22-6
ex2206
#include <stdio.h> #include <stdlib.h> int main() { FILE *handle; int highscore; handle = fopen("scores.dat","w"); if(!handle) { puts("File error!"); exit(1); } printf("What is your high score? "); scanf("%d",&highscore); fprintf(handle,"%d",highscore); fclose(handle); puts("Score saved"); return(0); }
Notes
* Up until the C99 standard, the b character was required when reading from or writing to binary files. So the fopen() function in Line 9 would read:
handle = fopen("scores.dat","wb");
Current compilers no longer need the b character and, if specified, it's ignored. Here are the comments from the current (C11) fopen() man page:
Copyright © 1997-2024 by QPBC.
All rights reserved