航班订票系统,录入航班,列出航班,在重新启动代码时还保存着上一次运行代码所录入的航班信息,c语言代码
时间: 2024-03-23 15:38:37 浏览: 62
模拟飞机票订票系统c语言源代码
5星 · 资源好评率100%
下面是一个简单的基于文件存储的航班订票系统的C语言代码,可以实现录入航班、列出航班、保存航班信息和重新读取航班信息等功能。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_FLIGHTS 100
struct flight {
char flight_num[10]; // 航班号
char departure[20]; // 出发地
char destination[20]; // 目的地
int seats; // 座位数
};
void save_flights(struct flight flights[], int num_flights) {
FILE *fp = fopen("flights.dat", "wb");
if (fp == NULL) {
printf("Error: cannot open file.\n");
return;
}
fwrite(flights, sizeof(struct flight), num_flights, fp);
fclose(fp);
}
int load_flights(struct flight flights[]) {
FILE *fp = fopen("flights.dat", "rb");
if (fp == NULL) {
return 0;
}
int num_flights = fread(flights, sizeof(struct flight), MAX_FLIGHTS, fp);
fclose(fp);
return num_flights;
}
void list_flights(struct flight flights[], int num_flights) {
printf("Flight Number\tDeparture\tDestination\tSeats\n");
printf("---------------------------------------------------\n");
for (int i = 0; i < num_flights; i++) {
printf("%s\t%s\t\t%s\t\t%d\n", flights[i].flight_num, flights[i].departure, flights[i].destination, flights[i].seats);
}
}
void add_flight(struct flight flights[], int *num_flights) {
if (*num_flights >= MAX_FLIGHTS) {
printf("Error: too many flights.\n");
return;
}
struct flight f;
printf("Enter flight number: ");
scanf("%s", f.flight_num);
printf("Enter departure: ");
scanf("%s", f.departure);
printf("Enter destination: ");
scanf("%s", f.destination);
printf("Enter number of seats: ");
scanf("%d", &f.seats);
flights[*num_flights] = f;
(*num_flights)++;
}
int main() {
struct flight flights[MAX_FLIGHTS];
int num_flights = load_flights(flights);
char choice;
do {
printf("\nFlight Reservation System:\n");
printf("1. List flights\n");
printf("2. Add a flight\n");
printf("3. Quit\n");
printf("Enter choice: ");
scanf(" %c", &choice);
switch (choice) {
case '1':
list_flights(flights, num_flights);
break;
case '2':
add_flight(flights, &num_flights);
break;
case '3':
save_flights(flights, num_flights);
printf("Exiting...\n");
break;
default:
printf("Invalid choice. Try again.\n");
}
} while (choice != '3');
return 0;
}
```
在程序启动时,我们先调用`load_flights`函数从文件中读取保存的航班信息。在录入新的航班信息时,将其添加到`flights`数组中,同时更新`num_flights`变量来记录航班数量。在程序退出前,我们调用`save_flights`函数将`flights`数组中的航班信息写入文件中,以便下次启动程序时可以重新读取。
阅读全文