簡體   English   中英

保存和從文件中提取數據

[英]Saving and fetching data from a file

我正在用C語言在Linux OS(ubuntu 12.04)上開發路由協議。 我的問題是我需要將路由表保存在外部文件中,這樣如果程序關閉或計算機關閉,程序應該能夠在重新啟動時從文件中獲取路由表。

什么是最簡單的解決方案? 如果你能解釋一下,我將不勝感激。 如果它可以幫助你回答,我在下面保存表struct routing user_list[40] :較小的索引在表中具有更高的優先級。

struct routing {
   int hop_distance;
   char senderID[16]; // 192.168.001.122
   char gateway[16];
};

struct routing user_list[40] = { [0] = {0, {0}, {0}, {0} } };

先感謝您。

男人畏懼

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
...
RETURN VALUE
fread()  and  fwrite() return the number of items successfully read or written (i.e., not the number of charac‐
ters).  If an error occurs, or the end-of-file is reached, the return value is a short item count (or zero).

最簡單的解決方案

int nb_written = fwrite(&user_list, sizeof(struct routing), 40, myfile);
int nb_read = fread(&user_list, sizeof(struct routing), 40, myfile);

如評論中所示:

  • 由於依賴於體系結構的int類型,生成的文件將不可移植。
  • 必須檢查返回的值以處理io錯誤

請參閱讀取寫入以保存此數據。 將IP地址存儲為二進制(即4個字節)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM