struct結構
struct array寫入binary file
size_t fwrite(const void *buf, size_t size, size_t n, FILE *fp)
size_t fread(void *ptr, size_t, size_t n, FILE *fp)
- 第一個參數傳的是要讀出或要寫入的起始位址,所以傳入陣列名稱即可。
- 第二個參數為每一個寫入/讀出資料的大小,由於一次寫入/讀取一個struct,所以為sizeof(struct Student)或sizeof(Student)
- 第三個參數為寫入/讀出的數目,故傳入array size。
- 第四個參數為文字檔的file handler。
#define NAME_LEN 11
#define ARRAY_SIZE 3
struct Student {
int id;
char name[NAME_LEN];
};
typedef struct Student Student;
int main() {
Student student0[ARRAY_SIZE]; // struct array for write
Student student1[ARRAY_SIZE]; // struct array for read
FILE *fp; // file handle
int i; // for loop counter
// input struct array
student0[0].id = 1;
strcpy(student0[0].name, "clare");
student0[1].id = 2;
strcpy(student0[1].name, "jingyi");
student0[2].id = 3;
strcpy(student0[2].name, "jessie");
// open binary file [write binary]
if (!(fp = fopen("library.dat", "wb")))
return -1;
// size_t fwrite(const void *buf, size_t size, size_t n, FILE *fp)
fwrite(student0, sizeof(Student), ARRAY_SIZE, fp);
fclose(fp); // close file
// open binary file [read binary]
if (!(fp = fopen("library.dat", "rb")))
return -1;
// size_t fread(void *ptr, size_t, size_t n, FILE *fp)
fread(student1, sizeof(Student), ARRAY_SIZE, fp);
for(i = 0; i != ARRAY_SIZE; ++i) {
printf("%d\n", student1[i].id);
printf("%s\n", student1[i].name);
}
fclose(fp);
}