- 程式 strunion1.c 定義 structure student 包含變數 char name[20], unsigned int sid, unsigned short score,從命令外加第一個參數指定的檔案讀入學生資料,當檔案不存在則印出「... NOT exists.」並回傳非 0 數字碼,檔案存在則將資料存入結構 student 中。
下載學生資料測試檔 grade.txt,依序印出 struct 的學生資料,每筆學生資料換行列印,每一橺位以 <TAB> 分隔,編譯成可執行檔 strunion1。輸出範例如下:
./strunion1 ggg.txt
ggg.txt NOT exist.
./strunion1 grade.txt
sid=27010 name=Alisa score=91
sid=27021 name=Brook score=35
sid=27091 name=Crystal score=76
sid=27102 name=Jenny score=60
- 承上題 strunion1.c,程式 strunion2.c,將印出 struct 的學生資料寫成函式 printgrade,傳入結構「內容」到函式 printgrade,編譯成可執行檔 strunion2。
- 承上題 strunion2.c,程式 strunion3.c,將印出 struct 的學生資料寫成函式 printgrade,傳入結構「指標」到函式 printgrade,編譯成可執行檔 strunion3。
- 承上題 strunion3.c,程式 strunion4.c,指定變數 score 位元數 6,因此 score 無法儲存 64 以上的數字,編譯成可執行檔 strunion4。以測試檔 grade.txt 測試結果如下,原先 score 高於 64 分以上的最高兩個位元不見,此列中都被減了 64。
./strunion4 grade.txt
sid=27010 name=Alisa score=27
sid=27021 name=Brook score=35
sid=27091 name=Crystal score=12
sid=27102 name=Jenny score=60
- 承上題 strunion1.c,程式 strunion5.c,student 由 structure 改成 union,且宣告 char name[13],並於最後印出 union student 所佔位元組數,編譯成可執行檔 strunion5。輸出範例如下,union 中三個成員都使用同一段記憶體,最後讀入的值是 score,所以 union student 三個成員輸出都一樣是 score,只是 name 以字元印出。
./strunion5 grade.txt
sid=91 name=[ score=91
sid=35 name=# score=35
sid=76 name=L score=76
sid=60 name=< score=60
sizeof(student)=16