我需要閱讀格式化文件,看起來像這樣。在C中讀取格式化文件比我做的更有效嗎?
代碼:HA-RK
名稱:奧斯卡
MRTE:火車
等
目前我的代碼看起來是這樣的。
FILE *file;
char unneeded[10];
char whitespace[2];
char actual[10];
file = fopen("scannertest.txt","r");
fscanf(file,"%s",unneeded); // this is the identifier and the colon (code:)
fscanf(file,"%[ ]",whitespace); // this takes in the white space after the colon.
fscanf(file,"%s",actual); // this is the value I actually need.
/**
* Do stuff with the actual variable
**/
fclose(file);
這樣對我的作品,但我不認爲在文本文件中的每一行寫三封fscanf()函數的是做到這一點的最好方式,尤其是因爲我將在循環中做後來。
我試圖做這樣的:
fscanf(file, "%s %[ ] %s",unneeded,whitespace,real);
然而,這給了我奇怪的符號,當我試圖打印輸出。
我嘗試使用上與fgets的sscanf()我是有這樣的。 fgets(line,20,file); sscanf(line,「%s%[]%s,unneeded,whitespace,actual); 但是,這仍然給我帶來了同樣的問題,奇怪的符號進入變量 – 2009-12-12 02:06:37
聽起來更像是溢出一個緩衝區if你會看到奇怪的符號,非常確定檢查sscanf的返回值,所以你知道它實際上讀取了一些東西。 – nos 2009-12-12 02:29:40