引言C语言作为一种基础且强大的编程语言,以其效率、灵活性和广泛的应用场景而闻名。通过开发一个图书管理系统,我们可以深入理解C语言的基础语法、结构化编程理念以及如何实现实际应用。本文将指导你如何使用C语...
C语言作为一种基础且强大的编程语言,以其效率、灵活性和广泛的应用场景而闻名。通过开发一个图书管理系统,我们可以深入理解C语言的基础语法、结构化编程理念以及如何实现实际应用。本文将指导你如何使用C语言创建一个简单的图书管理系统,帮助你轻松入门C语言编程。
在开始编程之前,我们需要明确图书管理系统的基本需求:
为了存储图书信息,我们可以定义一个结构体Book:
typedef struct { int id; char title[50]; char author[30]; float price; int quantity;
} Book;同样,用户信息可以存储在结构体User中:
typedef struct { int id; char name[50]; char password[50];
} User;void addBook(Book *books, int *count) { Book newBook; printf("Enter book ID: "); scanf("%d", &newBook.id); printf("Enter book title: "); scanf("%s", newBook.title); printf("Enter book author: "); scanf("%s", newBook.author); printf("Enter book price: "); scanf("%f", &newBook.price); printf("Enter book quantity: "); scanf("%d", &newBook.quantity); books[*count] = newBook; (*count)++;
}void deleteBook(Book *books, int *count) { int id; printf("Enter book ID to delete: "); scanf("%d", &id); for (int i = 0; i < *count; i++) { if (books[i].id == id) { for (int j = i; j < *count - 1; j++) { books[j] = books[j + 1]; } (*count)--; printf("Book deleted successfully.\n"); return; } } printf("Book not found.\n");
}void borrowBook(Book *books, int *count) { int id; printf("Enter book ID to borrow: "); scanf("%d", &id); for (int i = 0; i < *count; i++) { if (books[i].id == id && books[i].quantity > 0) { books[i].quantity--; printf("Book borrowed successfully.\n"); return; } } printf("Book not available or not found.\n");
}void returnBook(Book *books, int *count) { int id; printf("Enter book ID to return: "); scanf("%d", &id); for (int i = 0; i < *count; i++) { if (books[i].id == id) { books[i].quantity++; printf("Book returned successfully.\n"); return; } } printf("Book not found.\n");
}void addUser(User *users, int *count) { User newUser; printf("Enter user ID: "); scanf("%d", &newUser.id); printf("Enter user name: "); scanf("%s", newUser.name); printf("Enter user password: "); scanf("%s", newUser.password); users[*count] = newUser; (*count)++;
}void deleteUser(User *users, int *count) { int id; printf("Enter user ID to delete: "); scanf("%d", &id); for (int i = 0; i < *count; i++) { if (users[i].id == id) { for (int j = i; j < *count - 1; j++) { users[j] = users[j + 1]; } (*count)--; printf("User deleted successfully.\n"); return; } } printf("User not found.\n");
}为了将数据持久化存储,我们可以使用文件操作:
void saveData(Book *books, int count, const char *filename) { FILE *file = fopen(filename, "wb"); if (file == NULL) { printf("Error opening file.\n"); return; } fwrite(books, sizeof(Book), count, file); fclose(file);
}
void loadData(Book *books, int *count, const char *filename) { FILE *file = fopen(filename, "rb"); if (file == NULL) { printf("Error opening file.\n"); return; } while (fread(&books[*count], sizeof(Book), 1, file)) { (*count)++; } fclose(file);
}通过以上步骤,你已经成功创建了一个简单的图书管理系统。这个系统可以帮助你更好地理解C语言的基础语法和编程理念。随着你对C语言的熟练程度不断提高,你可以进一步扩展这个系统,增加更多功能,如图书分类、借阅统计等。祝你编程愉快!