我正在处理的程序会创建一个包含高分部分的文件(about.txt)。如何从文件中读取变量
在名为.txt线12 ...
纯文本(无高分):
- with <0>
C:
fprintf(about,"-%s with <%ld>",highname,highscore);
我需要阅读从比分该文件并在写入新文件之前测试它是否大于当前高分。
我需要......
if(score > highscore)
highscore=score;
唯一的问题是我如何从文件中得到高分。
我自己做了一些研究,我确定这比我做得更容易,但是当我环顾四周时我找不到任何方法来做到这一点。
谢谢。 /////////////////////////////////编辑/////////////// ///////// 创建文件:
FILE *about;
fpos_t position_name;
fpos_t position_score;
...
fprintf(about,"\n\nHIGHSCORE:\n\n");
fprintf(about,"-");
fgetpos(about,&position_name);
fprintf(about,"%s",highname);
fprintf(about,"with");
fgetpos(about,&position_score);
fprintf(about,"%ld",highscore);
fclose(about);
...
获取成绩:
FILE *about;
about = fopen("about.txt","r");
fseek(about,position_name,SEEK_SET);
fscanf(about,"%s",highname);
fseek(about,position_score,SEEK_SET);
fscanf(about,"%ld",highscore);
fclose(about);
改变变量(注..高分/ highname是全局变量)
if(score >= highscore) //alter highscore
{
highscore = score;
highname = name;
puts("NEW HIGHSCORE!!!\n");
}
我得到错误:
error: incompatible types when assigning to type 'char[3]' from type 'char'
在此行中:
highname = name;
名称/分/ highname这里声明(在头文件)/高分:
char name[3];
char highname[3];
long score;
long highscore;
究竟是什么,你有困难?打开文件,从中获取数据,读入/解析文本字符串,然后将文本转换为数字值?还有别的吗? –
您可以使用函数fscanf。它在与fprintf相同的库中定义。 – Wug