2013-05-04 74 views
0

起初,我在應用程序啓動時將所有變量加載到內存中。隨着時間的推移,變量的數量變得如此之大,我不想再這樣做了。 相反,我只在需要時才檢索它們(使用映射文件,但那是另一回事)。文件中的數據位置

起初我寫的變量到一個文件中。 (這是重複多次的...)

vector<udtAudioInfo>::iterator it = nAudioInfos.Content().begin(); 
for (;it != nAudioInfos.Content().end(); ++it) 

    //I think here I should store the position where the data will begin in the file 
    //I still need to add code for that... 

    //now write the variables 
    fwrite(&it->UnitID,sizeof(int),1,outfile); 
    fwrite(&it->FloatVal,sizeof(double),1,outfile); 

    //I think here I should store the length of the data written 
    //I still need to add code for that... 
} 

但現在,我需要動態地加載變量,我需要跟蹤的其實都是存儲在哪裏。

我的問題是:我怎麼能找出當前寫入位置?我認爲並希望我可以使用它來跟蹤數據實際駐留在文件中的位置。

+0

你有沒有看着'ftell'? – GWW 2013-05-04 19:45:20

回答

1

因爲你是在讀或寫變量您可以使用函數ftell()

例如,在你上面的例子代碼,你可以在每次迭代開始找到的位置:

當你準備回到那個位置,你可以使用fseek()。 (下面,SEEK_SET使得相對於文件的起始位置。)

fseek (infile, position, SEEK_SET); 
+0

啊,很酷,謝謝。 – tmighty 2013-05-04 19:52:31

0

我建議你一次讀取所有的變量,也許用一個結構:

struct AppData 
{ 
    udtAudioInfo audioInfos[1024]; 
    int infoCount; 

    ... // other data 
}; 

,然後加載/保存通過:

AppData appData; 
fread(appData, 1, sizeof(AppData), infile); 
... 
fwrite(appData, 1, sizeof(AppData), outfile); 

實際上,這將比多個讀/寫操作快得多。

相關問題