C语言用链表实现顾客根据TXT文件中菜品信息完成对订单的增删改查,并输出txt文件
时间: 2023-05-22 10:05:55 浏览: 113
基于C语言链表实现的订餐系统_C语言_
5星 · 资源好评率100%
非常感谢您的提问!以下是C语言用链表实现顾客根据TXT文件中菜品信息完成对订单的增删改查,并输出txt文件的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct dish {
int id;
char name[50];
int price;
struct dish *next;
} Dish;
Dish *head, *tail;
Dish *createDish(int id, char *name, int price) {
Dish *dish = (Dish*)malloc(sizeof(Dish));
dish->id = id;
strcpy(dish->name, name);
dish->price = price;
dish->next = NULL;
return dish;
}
void addDish(int id, char *name, int price) {
Dish *dish = createDish(id, name, price);
if (head == NULL) {
head = dish;
} else {
tail->next = dish;
}
tail = dish;
}
void displayDishes() {
Dish *dish = head;
while (dish != NULL) {
printf("%d\t%s\t%d\n", dish->id, dish->name, dish->price);
dish = dish->next;
}
}
void freeDishes() {
Dish *dish = head;
while (dish != NULL) {
Dish *temp = dish->next;
free(dish);
dish = temp;
}
head = NULL;
tail = NULL;
}
void readDishes(char *filename) {
FILE *file = fopen(filename, "r");
if (file == NULL) {
printf("Failed to read file: %s\n", filename);
return;
}
char line[100];
while (fgets(line, sizeof(line), file)) {
int id, price;
char name[50];
sscanf(line, "%d,%[^,],%d", &id, name, &price);
addDish(id, name, price);
}
fclose(file);
}
void saveDishes(char *filename) {
FILE *file = fopen(filename, "w");
if (file == NULL) {
printf("Failed to save file: %s\n", filename);
return;
}
Dish *dish = head;
while (dish != NULL) {
fprintf(file, "%d,%s,%d\n", dish->id, dish->name, dish->price);
dish = dish->next;
}
fclose(file);
}
void addOrder(int id, int quantity) {
Dish *dish = head;
while (dish != NULL) {
if (dish->id == id) {
dish->price *= quantity;
return;
}
dish = dish->next;
}
printf("Dish not found with id: %d\n", id);
}
void removeOrder(int id) {
Dish *dish = head;
if (dish->id == id) {
head = dish->next;
free(dish);
return;
}
while (dish->next != NULL) {
if (dish->next->id == id) {
Dish *toDelete = dish->next;
dish->next = toDelete->next;
free(toDelete);
return;
}
dish = dish->next;
}
printf("Dish not found with id: %d\n", id);
}
void updateOrder(int id, int newPrice) {
Dish *dish = head;
while (dish != NULL) {
if (dish->id == id) {
dish->price = newPrice;
return;
}
dish = dish->next;
}
printf("Dish not found with id: %d\n", id);
}
int main() {
readDishes("dishes.txt");
printf("Menu:\n");
displayDishes();
addOrder(1, 2);
printf("Order updated:\n");
displayDishes();
removeOrder(2);
printf("Order removed:\n");
displayDishes();
updateOrder(3, 50);
printf("Order updated:\n");
displayDishes();
saveDishes("dishes_new.txt");
freeDishes();
return 0;
}
```
至于"lua closure factory 完整代码"和"中文加密"的问题,我需要您提供更具体的问题或背景信息,我将会尽力回答。
阅读全文