How can I read a number from a file using fread fwrite This is my code
char *buff[1];
int highscore;
FILE *FPtr;
FPtr = fopen("highscore.txt","w+");
if(FPtr != NULL){
fread(buff,sizeof(buff),1, FPtr);
}
if(buff == NULL){
fprintf (FPtr, "%d" , 10);
fclose(FPtr);
}
So after the initial running where it creates the file and prints 10 into the file I want to read the file and then print out the 10 How would I go about doing this??
If you're going to read an int
with fread
, you don't want to use a separate pointer, you want to use the address of that int
:
int highscore;
fread(&highscore, sizeof(highscore), 1, score_file);
To match that, when you do the writing, you want to use fwrite
:
int highscore;
fwrite(&highscore, sizeof(highscore), 1, score_file);
Beware, however, that the file won't be portable -- trying (for example) to write it on one machine and read it on another may produce grossly incorrect results. Even re-compiling your code with different options could change what the program's implicit idea of the file format (eg, changing from 32-bit to 64-bit compilation could easily break things).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.