在我的程序中,我從鍵盤接收輸入。我把這個輸入放在一個包含兩個char
字段和1 int
字段的struct
中。我怎樣才能使用函數寫入整個struct
?如何在文件中寫入完整的結構?
我不要想要分別寫入struct
的每個成員。
在我的程序中,我從鍵盤接收輸入。我把這個輸入放在一個包含兩個char
字段和1 int
字段的struct
中。我怎樣才能使用函數寫入整個struct
?如何在文件中寫入完整的結構?
我不要想要分別寫入struct
的每個成員。
這取決於您的struct
是如何定義的,您是否希望您的輸出是人類可讀的,以及是否要在不同的體系結構上讀取輸出文件。
的fwrite
解決方案,別人給予將寫入結構到輸出文件的二進制表示。例如,給定代碼如下:
#include <stdio.h>
int main(void)
{
struct foo {
int x;
char name1[10];
char name2[10];
} items[] = {{1,"one","ONE"}, {2,"two","TWO"}};
FILE *output = fopen("binio.dat", "w");
fwrite(items, sizeof items, 1, output);
fclose(output);
return 0;
}
如果我顯示binio.dat
內容到控制檯,得到以下:
[email protected]:~/Development/Prototypes/C/binio$ cat binio.dat [email protected]:~/Development/Prototypes/C/binio$ [email protected]:~/Development/Prototypes/C/binio$ od -c binio.dat 0000000 001 \0 \0 \0 o n e \0 \0 \0 \0 \0 \0 \0 O N 0000020 E \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 0000040 \0 \0 \0 \0 002 \0 \0 \0 t w o \0 \0 \0 \0 \0 0000060 \0 \0 T W O \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 0000100 \0 \0 \0 \0 \0 \0 \0 \0 0000110
的整數值顯示爲垃圾(上面未重放)因爲它們已經以字節序列01,00,00,00和02,00,00,00(x86是little-endian)存儲,它們不是可打印字符。還要注意,name1
的所有10個字符和name2
的所有20個字符都被寫入該文件,該文件可能是或不是您想要的。
的情況得到,如果你的結構包含更加複雜的指針,因爲什麼被存儲到文件指針值,而不是被指着的事情:
#include <stdio.h>
int main(void)
{
struct foo {
int x;
char *name1;
char *name2;
} items[] = {{1,"one","ONE"}, {2,"two","TWO"}};
FILE *output = fopen("binio.dat", "w");
fwrite(items, sizeof items, 1, output);
fclose(output);
return 0;
}
這一次我得到
[email protected]:~/Development/Prototypes/C/binio$ cat binio.dat ��������[email protected]:~/Development/Prototypes/C/binio$ [email protected]:~/Development/Prototypes/C/binio$ od -c binio.dat 0000000 001 \0 \0 \0 260 205 004 \b 264 205 004 \b 002 \0 \0 \0 0000020 270 205 004 \b 274 205 004 \b 0000030
請注意,根本沒有任何字符串出現在文件中;如果您使用不同的程序讀取此文件,它將看到的所有內容(很可能)都是無效地址。
如果你希望你的輸出爲人類可讀和你希望能夠在不同的體系結構來讀取這些值,你幾乎必須去與格式化輸出,這意味着你必須單獨寫每個成員:
#include <stdio.h>
int main(void)
{
struct foo {
int x;
char *name1;
char *name2;
} items[] = {{1,"one","ONE"}, {2,"two","TWO"}};
FILE *output = fopen("binio.dat", "w");
int i;
for (i = 0; i < sizeof items/sizeof items[0]; i++)
{
fprintf(output, "%d %s %s\n", items[i].x, items[i].name1, items[i].name2);
}
fclose(output);
return 0;
}
[email protected]:~/Development/Prototypes/C/binio$ cat binio.dat 1 one ONE 2 two TWO
你當然可以換行操作在你自己的功能,像
int printFoo(FILE *output, const struct foo item)
{
return fprintf(output, "%d %s %s\n", item.x, item.name1, item.name2);
}
,但最終,這個過程非常簡單。
如果您不關心可讀性和可移植性,fwrite
解決方案的效果很好,但如果在結構中有任何指針成員,您仍然必須小心。
C沒有「說明」。
您應該能夠使用一個單一的函數調用,如:
fwrite(&mystructure, sizeof mystructure, 1, myfile);
但是,這也不是沒有缺點:
目前還不清楚你在問什麼。你可以添加一些代碼到你的問題,所以我們可以更好地理解它? – 2013-03-20 11:37:49
只需將指針的結構傳遞給指令即可。你不需要寫成員。 – Abhineet 2013-03-20 11:41:03
我會稍後添加,現在我只能使用智能手機進行互聯網 – Mitro 2013-03-20 11:49:01