我正在處理的程序會創建一個包含高分部分的文件(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