I'd like to record the number of rock-paper-scissors matches and the record of winning or losing in a .txt file, but if you keep the source code below that I made, the record will not be accumulated in the file.How can I make changes to build up my record?
I've been stuck here for a while, so I'd appreciate it if you could let me know if anyone understands.Thank you for your cooperation.
Supplement: Read defines a function, but writes are in int main().I'm sorry if it's hard to understand.
#include<stdio.h>
# include <time.h>
# include <stdlib.h>
# include "jankendata.txt"
void Read(const char*file){
FILE*fp;
if(((fp=fopen("jankendata.txt", "r"))==NULL){
printf("Run First Time\n";
} else {
int battle = 0, win = 0, loss = 0, draw = 0;
fscanf(fp, "%d%d%d%d", & battle, & win, & loss, & draw);
printf("%d Battle %d Victory %d Loss %d Draw\n", battle, win, loss, draw);
fclose(fp);
}
}
int main (void)
{
const char*file="jankendata.txt";
int battle = 0, win = 0, loss = 0, draw = 0;
int me, npc, result;
FILE*fp;
Read (file);
// Choose the way you want to make it
printf("Choose your hand ->\n[Goo]:0[Choki]:1[par]:2 End:3
\n");
scanf("%d", & me);
if(me==0||me==1||me==2||me==3){
} else{
printf("Please select a number from 0 to 3.\n");
scanf("%d", & me);
}
// npc's hand selection
sland(time(NULL)));
npc = land()%3;
printf("The opponent got %d!\n", npc);
// Compare yourself with the other person and display the results
result=(me-npc+3)%3;
if(result==2){
printf("Your Victory\n");
win++;
} else if(result==1){
printf("Your Losing\n");
lose++;
} else if(result==0){
printf("Draw\n");
draw++;
}
if(((fp=fopen("jankendata.txt", "w"))==NULL){
printf("\a file cannot be expanded.\n");
} else{
battle=win+lose+draw;
fprintf(fp, "%d%d%d%d%d\n", battle, win, loss, draw);
fclose(fp);
}
return EXIT_SUCCESS;
}
fopen
opens the file to record the results, and w
is specified in the mode.
This will destroy the original contents every time you open the file.
Original Code:
if((fp=fopen("jankendata.txt", "w"))==NULL){
If you want to keep the original content and add it, try specifying a
instead.
modification examples:
if((fp=fopen("jankendata.txt", "a"))==NULL){
Note:
How to open and close C language files [how to use fopen and fclose]
© 2024 OneMinuteCode. All rights reserved.