C 檔案方式讀寫結構體探析

2021-08-17 05:35:04 字數 2145 閱讀 6948

最近一直在研究.net micro framework字型檔案(tinyfnt),由於tinyfnt檔案頭部有一段描述資料,所以很想定義乙個結構體,像vc一樣直接從檔案中讀出來,省得用流乙個個解析很是麻煩。

沒有想到在c#中竟沒有直接的指令,想必c#設計者認為提供了流和序列化技術,一切問題都可以迎刃而解了。

在c#中結構體是乙個比較複雜的東西,在此之上有很多需要設定的引數,否則用起來就很容易出錯。下面是msdn上一段描述,看看也許有助於理解c#語言中的結構體。

-------------------------

通過使用屬性可以自定義結構在記憶體中的布局方式。例如,可以使用 structlayout(layoutkind.explicit) 和 fieldoffset 屬性建立在 c/c++ 中稱為聯合的布局。

[system.runtime.interopservices.structlayout(layoutkind.explicit)]

struct testunion

在上乙個**段中,

testunion

的所有欄位都從記憶體中的同一位置開始。

以下是字段從其他顯式設定的位置開始的另乙個示例。

[system.runtime.interopservices.structlayout(layoutkind.explicit)]

struct testexplicit

i1和 i2

這兩個 int 字段共享與 lg

相同的記憶體位置。使用平台呼叫時,這種結構布局控制很有用。

-------------------------

我做了乙個簡單的測試程式,基本達成預定需求,不過程式該方式要求比較苛刻,如果要解析的資料與轉換的結構體不匹配就會引發一系列莫名其妙的異常(如記憶體不可讀等等之類),下面是測試程式的源**,有興趣的朋友可以看一看,也希望網友能提出更好的方案。

using system;

using system.collections.generic;

using system.componentmodel;

using system.data;

using system.drawing;

using system.text;

using system.windows.forms;

using system.io;

using system.runtime.interopservices;

namespace rwfile

//從檔案中讀結構體

private

void button1_click(object sender, eventargs e)

filestream fs = new

filestream(strfile, filemode.open, fileaccess.readwrite);

teststruct ts = new

teststruct();

byte bytdata = new

byte[marshal.sizeof(ts)];

fs.read(bytdata, 0, bytdata.length);

fs.close();

ts = rawdeserialize(bytdata);

textbox1.text = ts.dtest.tostring();

textbox2.text = ts.utest.tostring();

textbox3.text = encoding.default.getstring(ts.btest);}//

向檔案中寫結構體

private

void button2_click(object sender, eventargs e)

[structlayout(layoutkind.sequential,charset = charset.ansi)] //,size=16

public

struct

teststruct

//序列化 public

static

byte rawserialize(object obj)

//反序列化

public

static

teststruct rawdeserialize(byte rawdatas)

}

C 檔案方式讀寫結構體探析

最近一直在研究.net micro framework字型檔案 tinyfnt 由於tinyfnt檔案頭部有一段描述資料,所以很想定義乙個結構體,像vc一樣直接從檔案中讀出來,省得用流乙個個解析很是麻煩。沒有想到在c 中竟沒有直接的指令,想必c 設計者認為提供了流和序列化技術,一切問題都可以迎刃而解...

C 結構體讀寫操作

今天再寫乙個練手的程式的時候,忘記了c 關於結構體的檔案讀寫操作,於是在網上找了好多,但是都是有些問題的,經過一番探索終於解決了在檔案中讀寫結構體的問題,下面就是我的解決方法。首先程式裡要用到ifstream的eof 函式,以及open 函式開啟檔案,底下的就是我的 struct student s...

C語言結構體讀寫

實驗環境fedora33 qt5.12 背景 哈夫曼編碼 每個結點包含了字元和對應的權值等資訊,最好記錄在檔案裡,每次執行 從檔案裡讀取結點資訊 1 include 2 3 typedef struct 4newnode 89 void inputinfo int n 10 11int main 1...