我用c++寫了一個 Book的結構體,想要把Book的信息存入文件中,利用fwrite向文件
中寫入的時候,我循環了100次,也就是向文件中存入了100本書,可是往外讀取的時候,
前25本正常,後面就亂了,是在搞不明白哪裡出問題了,但是在linux下運行正常。以下是代碼,其中save()為文件操作
void addBooksByBatch(int k) {
for (int i = 1; i < k; i++) {
BookInfo bookInfo;
sprintf(bookInfo.name, "%d", i);
sprintf(bookInfo.writer, "%d", i);
sprintf(bookInfo.press, "%d", i);
bookInfo.ISBN = i;
bookInfo.price = 20;
bookInfo.exist = 1;
save(bookInfo, 5);
}
}
void save(BookInfo bookInfo, int num) { //num表示書的本數
FILE *bookFile = fopen("book", "ab+");
fseek(bookFile, 0, SEEK_END);
int position = ftell(bookFile);
bookInfo.index = position;
Book book;
book.exist = 1;
book.flag = 1;
for (int i = 0; i < num; i++) {
book.callnumber = bookInfo.ISBN * N + i;
if (i == num - 1) {
book.next = -1;
}
else {
book.next = position + BOOK_SIZE;
}
fwrite(&book, BOOK_SIZE, 1, bookFile);
position = ftell(bookFile);
}
fclose(bookFile);
FILE *bookInfoFile = fopen("bookinfo", "ab+");
fwrite(&bookInfo, BOOKINFO_SIZE, 1, bookInfoFile);
fclose(bookInfoFile);
cout << "圖書添加完畢" << endl;
}
你這是按二進制格式讀寫,修改下面兩句話就行了。
FILE *bookInfoFile = fopen("bookinfo", "wb");
FILE *p = fopen("bookinfo","rb");