用c语言编写图书馆管理系统中(3)图书的借阅和归还:包括图书的借阅记录 查询、借阅图书、归还图书代码及代码注释
时间: 2024-09-20 09:05:23 浏览: 113
在C语言中,创建一个简单的图书馆管理系统涉及到基本的数据结构,如链表用于存储图书信息和借阅记录。以下是图书借阅和归还功能的大致代码实现:
```c
#include <stdio.h>
#include <stdlib.h> // 包含内存管理函数
// 定义图书结构体
typedef struct {
char book_id[20];
char title[50];
int available; // 图书是否可供借阅,0表示已借出
} Book;
// 定义借阅记录结构体
typedef struct {
Book* book;
time_t borrow_date;
} BorrowRecord;
// 链表头结点
typedef struct Library {
Book* books;
BorrowRecord* borrow_records;
int size;
} Library;
// 功能函数声明
void init_library(Library* lib);
Book* find_book_by_id(Library* lib, char id[]);
BorrowRecord* add_borrow_record(Library* lib, Book* book);
void return_book(Library* lib, BorrowRecord* record);
// 主程序入口
int main() {
Library library;
init_library(&library);
// 示例操作:借书
Book* book = find_book_by_id(&library, "001");
if (book->available) {
BorrowRecord* new_record = add_borrow_record(&library, book);
printf("Book %s has been borrowed.\n", book->title);
free(book); // 回收不再使用的图书内存
} else {
printf("Book is not available.\n");
}
// 示例操作:归还图书
BorrowRecord* record = ...; // 获取需要归还的记录
return_book(&library, record);
printf("Book %s returned successfully.\n", record->book->title);
return 0;
}
// 初始化库
void init_library(Library* lib) {
lib->books = NULL;
lib->borrow_records = NULL;
lib->size = 0;
}
// 查找图书
Book* find_book_by_id(Library* lib, char id[]) {
for (int i = 0; i < lib->size; i++) {
if (!strcmp(lib->books[i].book_id, id)) {
return &lib->books[i];
}
}
return NULL;
}
// 添加借阅记录
BorrowRecord* add_borrow_record(Library* lib, Book* book) {
BorrowRecord* new_record = (BorrowRecord*)malloc(sizeof(BorrowRecord));
new_record->book = book;
new_record->borrow_date = time(NULL);
*lib->borrow_records = *new_record; // 将新记录添加到链表头部
lib->borrow_records++;
lib->size++;
return new_record;
}
// 归还图书
void return_book(Library* lib, BorrowRecord* record) {
// 更新书籍可用状态
record->book->available = 1;
// 移除借阅记录
if (lib->borrow_records == record) { // 如果是最新的借阅记录
lib->borrow_records--;
} else {
BorrowRecord** prev = &lib->borrow_records;
while (*prev != record) {
prev = &(*prev)->next;
}
*prev = record->next;
}
free(record); // 回收不再使用的记录内存
}
```
阅读全文