簡體   English   中英

如何將文件的內容讀取到靜態聲明的變量中?

[英]How to read contents of a file to a statically declared variable?

我有一個二進制數據文件,其中前四個字節是我想讀取的一些 integer。 我只是這樣做:

int * num_rounters_p = malloc(sizeof(int));
fread(num_rounters_p, 4, 1, p_file);

printf("%d\n", *num_routers_p); // 10

這很好用(如果沒有,請告訴我),但是我確實知道這個特定值的大小。 因此實際上沒有必要動態存儲它。

是否可以做類似的事情

int x = some_read_function(4, 1, p_file);

printf("%d\n", x); // 10

基本上將值存儲在堆棧而不是堆上? 上面的代碼示例當然不是基於 C,但我希望我明白我的意思:))

最直接的方法是

int num_routers;
size_t items_read = fread( &num_routers, sizeof num_routers, 1, p_file );

if ( items_read < 1 )
{
  // read error, handle as appropriate
}
else
{
  // do something with num_routers
}

不保證int為 4 字節寬,僅保證至少為2 字節寬,因此使用sizeof num_routers比使用文字4更安全。 當然,這假設二進制文件是在您正在讀取的同一平台上編寫的。

非易失性。 輕松修復:只需執行以下操作:

int num_routers;
fread(&num_routers, sizeof(int), 1, p_file);

暫無
暫無

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

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