0% found this document useful (0 votes)
23 views46 pages

Bus Ticket Booking System Project Report

The document is a project report for a Bus Ticket Booking System developed by students at Mahendra College of Engineering as part of their Bachelor of Engineering in Information Technology. It outlines the system's objectives, features, and design, emphasizing a user-friendly interface for real-time bus ticket reservations. The report includes acknowledgments, an abstract, system analysis, design specifications, and code snippets demonstrating the implementation of the project.

Uploaded by

harishmani250208
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views46 pages

Bus Ticket Booking System Project Report

The document is a project report for a Bus Ticket Booking System developed by students at Mahendra College of Engineering as part of their Bachelor of Engineering in Information Technology. It outlines the system's objectives, features, and design, emphasizing a user-friendly interface for real-time bus ticket reservations. The report includes acknowledgments, an abstract, system analysis, design specifications, and code snippets demonstrating the implementation of the project.

Uploaded by

harishmani250208
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

BUS TICKET BOOKING SYSTEM

A PROJECT REPORT

SUBMITTED BY
INBARASAN K
ARUL MURUGAN M
MANUJ M
AARVALAN V

INPARTIALFULFILLMENTFOR THE AWARD OF THE DEGREE


OF
BACHELOROF ENGINEERING
IN
INFORMATION TECHNOLOGY

MAHENDHRACOLLEGEOFENGINEERING, MINNAMPALLI
SALEM-636106

ANNAUNIVERSITY: CHENNAI 60025


BONAFIED CERTIFICATE

CERTIFIED THAT THIS PROJECT REPORT “...BUS TICKET BOOKING SYSTEM ... ‘’
IS THE BONAFIED WORK OF “............................................”REG NO..................................
WHO CARRIED OUT THE PROJECT WORK UNDER MY SUPERVISION DURING THE

ACADEMIC YEAR 2025-2026

HEAD OF THEDEPRTMENT STAFF-IN-CHARGE


SIGNATURE: SIGNATURE:

DEPARTMENT OF DEPARTMENT OF

“INFORMATION TECHNOLOGY” “INFORMATION TECHNOLOGY”

MAHENDRA COLLEGE OF ENGINEERING MAHENDHRA COLLEGE OF ENGINEERING

SALEM-CAMPUS, ATTUR MAINROAD, SALEM-CAMPUS, ATTUR MAIN ROAD,

MANNAMPALLI, SALEM-636106 MANNAMPALLI, SALEM-636106


AKNOLEDGEMENT

We express our sincere gratitude to all those who guided and supported us
throughout the completion of this project, "BUS TICKET BOOKING SYSTEM."
Their invaluable assistance, insightful suggestions, and continuous encouragement
were instrumental in turning our efforts into reality.
We offer our heartfelt thanks to Anna University, Chennai 600 025 for providing
us with the opportunity and the academic framework to undertake this project as
partial fulfillment for the award of the degree of Bachelor of Engineering in
Information Technology.
We are deeply indebted to our college, Mahendhra College of Engineering,
Minnampalli, Salem-636106, for providing the necessary facilities and a
conducive learning environment. We extend our profound thanks to the Head of the

Department (HOD) of the


Department of Information Technology, for their cooperation and guidance
throughout the project period. We express our sincere gratitude to our Staff-In-

Charge and supervisor, for their


constant guidance, patient supervision, critical advice, and constructive feedback,
which were crucial to the successful completion of this project. We also thank all the

faculty members of the Department of Information


Technology for their valuable suggestions and support during our study.
Finally, we would like to thank our family and friends for their unwavering moral
support, motivation, and belief in us.
ABSTRACT

This project details the development of a Bus Ticket Booking System


(BTBS), a console-based application implemented using C/C++ for a
Computer Programming Course (CPC) mini-project.
The core objective is to create an efficient, digitized solution for
managing bus ticket reservations, thereby replacing manual, error-prone
procedures. The system is designed to allow passengers to easily search
for buses based on route and date, view real-time seat availability, and
successfully book tickets.

Key programming concepts utilized include:

• Data Structures (e.g., struct): To organize complex entities like

Bus details, Route information, and Passenger records.


• File Handling: To ensure data persistence by storing crucial
information (routes, schedules, and booked tickets) in external data
files.

• Modular Programming: Using separate functions for tasks such


as seat selection, fare calculation, and administrator management.

The BTBS serves as a practical demonstration of applying fundamental


programming logic and data management principles to solve a real-
world problem, providing a functional model for automated
transportation ticketing.
1. Project Introduction: Single-Page Bus Ticket Booking System

1.1 Overview and Rationale


The modern traveler demands convenience, speed, and real-time
information when planning journeys. Traditional methods of ticket
booking, involving physical visits to ticket counters or navigating multi-
step, slow-loading websites, often lead to frustration, time wastage, and
uncertainty regarding seat availability. Furthermore, these methods
frequently lack dynamic updates and secure digital payment options.
This project addresses these challenges by proposing a Single-Page Bus
Ticket Booking System (SPBTBS). The system is designed to provide
a highly efficient, user-friendly, and responsive interface for searching,
selecting, and booking bus seats instantly. By leveraging modern web
technologies, the SPBTBS aims to centralize the entire booking process
into one cohesive view, minimizing page reloads and maximizing user
experience.

1.2 Problem Statement


Existing booking platforms often suffer from complex navigation, poor
mobile responsiveness, and delayed updates on seat availability, leading
to abandoned transactions and customer dissatisfaction. A key
requirement is a system that can handle high concurrent loads while
ensuring atomic transactions (i.e., preventing double-booking of seats)
and providing instant ticket confirmation.
1.3 Proposed Solution and Scope

The SPBTBS will beimplementedas a robust, client-centric Single-


Page Application (SPA).Theprimary features within the scope of this
project include:

1. Real-Time Search: Instant filtering of bus services based on


origin, destination, and date.
2. Interactive Seat Layout: A dynamic, visual representation of the
bus seating plan allowing users to select or deselect seats with
immediate price calculation.
3. Secure Booking Checkout: A streamlined one-step form for
passenger details and integrated payment gateway simulation.
4. Instant Confirmation: Generation of a digital ticket/e-mail
confirmation upon successful payment.

The focus is on delivering a seamless, end-to-end user experience on a


single, responsive interface, establishing a benchmark for simplicity and
speed in the travel technology sector.
2. System Analysis and Design

This section details the formal requirements and the architectural blueprint for the
Single-Page Bus Ticket Booking System (SPBTBS).
2.1 System Analysis

2.1.1 Functional Requirements (FR)

These define the specific actions the system must perform to satisfy user needs.

ID Module Requirement Description

FR01 Search Users must be able to search for available buses by


entering Origin, Destination, and Date of Travel.
The system must display a list of available buses with
FR02 Display key details (Bus Operator, Departure Time, Arrival
Time, Price, Available Seats).

Users must be able to view an interactive seat map


FR03 Seat and select one or more available seats.
Selection The system must temporarily reserve selected seats
for a fixed time window (e.g., 5 minutes) during
FR04 Booking checkout.

Users must input required passenger information


(Name, Age, Gender, Contact).
The system must simulate a secure payment gateway
FR05 Passenger
Details integration for processing transactions.

FR06 Payment
FR07 Confirmation Upon successful payment, a confirmation summary
(digital ticket) must be generated and displayed
instantly.
A mock administration interface must allow bus
FR08 Admin operators to add/update bus schedules and routes.
(Mock)

2.1.2 Non-Functional Requirements (NFR)

These define criteria used to judge the operation of the system, rather than
specific behaviors.

ID Category Requirement Description

NFR01 Performance The search results page must load within 2 seconds, even with
a large dataset.

NFR02 Usability The entire booking process must be completed within a single,
responsive page (SPA design).

NFR03 Security All data transmission, especially payment details (simulated),


must be encrypted (HTTPS simulation).

NFR04 Reliability The system must prevent concurrent users from booking the
same seat (atomic transaction guarantee).

NFR05 Maintainability Code must be modular, well-commented, and easily


extensible for adding new operators or payment methods.
2.2 System Design

2.2.1 Architectural Design

The SPBTBS will follow a Client-Centric Single-Page Application (SPA)


architecture layered on a standard three-tier model:

1. Presentation Tier (Client): The user interface (HTML/CSS/JavaScript)


responsible for rendering the single-page view, handling user interaction,
and making API calls.
2. Application Tier (Server/API): The backend logic responsible for processing
requests, enforcing business rules (e.g., seat reservation logic), and
connecting to the database.
3. Data Tier (Database): The persistent storage mechanism (e.g., Firestore)
used to store all system data, including Routes, Schedules, Buses, Seats, and
Bookings.

2.2.2 Data Design (Entity-Relationship Model)

The core entities and their relationships define how data is structured and stored to
support the booking logic.

Entity Attributes (Key Fields) Relationship

Route Rou teI (PK), , ,


D OriginDestinationDuration 1:M with
Schedule
Bus Bus ID(PK), OperatorName, Model, TotalSeats 1:M with
Schedule

Schedule Sch edu le (PK), D DepartureTime, Fare M:1 with


(FK), B usI (FK),
ID Rou te ID
Route and
Bus

Seat SeatID (PK), Sc he dul eI D SeatNumber, Status(Available,


(FK), M:1 with
Reserved, Booked) Schedule

Booking BookingID (PK), ScheduleID (FK), PassengerName, Contact, M:1 with


TotalFare, BookingStatus Schedule

2.2.3 Module Breakdown


The system functionality is segmented into four primary modules:

1. Search Module: Handles user input for travel parameters and


communicates with the backend to fetch filtered schedules.
2. Seat Selection Module: Manages the interactive seat map,
calculates the running total, and handles temporary seat
reservations.
3. Checkout Module: Collects passenger details, validates inputs, and
manages the payment process flow.
4. Data Management Module: The backend logic responsible for
retrieving and updating data in the database (e.g., marking a seat as
'Booked' and storing the ticket record).
System Flowchart (Process Flow Diagram)

This flowchart illustrates the primary process flow of the Single-Page Bus Ticket Booking
System (SPBTBS), detailing the interaction between the user and the system's core modules.
12. Decision: Application The system verifies the payment outcome. FR06
Payment Status Tier

13. Successful Data (IF YES): The system updates the seat FR07
Booking Management status from 'Reserved' to 'Booked', creates
Module a permanent record in the Booking entity,
and generates the digital ticket.

14. Confirmation Confirmation A digital ticket summary, including the FR07


Display Module Booking ID and PNR (mock), is
displayed to the user.

15. Failed Data (IF NO): The temporary reservation is FR04


Payment/Timeout Management released (seats revert to 'Available'), and
Module the user is prompted to retry payment or
adjust the selection.

16. End Booking The transaction is finalized.


Complete
Modules Description (Functions) – Bus Ticket
Booking System (C Programming)

1. Main Module

Function: main()

• Acts as the entry point of the program.


• Displays the main menu
(Book Ticket, Cancel Ticket, View Bus Details, View Bookings, Exit).
• Calls other modules based on user choice.

2. Bus Details Module

Function: displayBusDetails()

• Shows list of available buses.


• Displays: Bus Number, Route, Time, Fare, Total Seats.

Function: loadBusData()

• Reads bus data from a file (if implemented).


• Initializes bus information into structures.
3. Ticket Booking Module

Function: bookTicket()

• Takes passenger details (Name, Age, Gender).


• Displays buses and selects a bus number.
• Checks seat availability.
• Books a ticket and assigns a seat number.

Function: checkSeatAvailability(int busNo)

• Verifies if seats are available for the selected bus.


• Returns available seat count.

Function: generatePNR()

• Creates a unique PNR number using random or time-based logic.

Function: saveBookingToFile()

• Stores booking details into a file:


PNR, Passenger Name, Bus No, Seat No, Fare, Date.

4. Ticket Cancellation Module

Function: cancelTicket()

• Accepts PNR number from user.


• Searches for booking in file/structure.
• Marks the ticket as cancelled and frees the seat.

Function: updateSeatAfterCancel(int busNo)

• Increases seat count when a ticket is cancelled.


5. View Bookings Module

Function: viewBookings()

• Displays all confirmed bookings.


• Shows PNR, Passenger Name, Bus No, Seat No.

Function: searchBooking(int pnr)

• Searches for a specific booking using PNR.


• Used for both viewing and cancellation.

6. Fare Calculation Module

Function: calculateFare(int busNo, int seats)

• Calculates total fare.


• Fare = Seat Fare × Number of Seats.
• Returns final amount.

7. Input Validation Module

Function: validateName(char name[])

• Ensures name contains only alphabets.

Function: validateBusNo(int busNo)

• Checks if bus number exists in the system.

Function: validatePNR(int pnr)

• Ensures PNR is correctly formatted and exists.


8. File Handling Module

Function: readFromFile()

• Loads bookings/bus data from a file when the program starts.

Function: writeToFile()

• Saves all updates (bookings/cancellations) before exit.

9. Utility Module

Function: clearScreen()

• Clears console screen (platform-dependent).

Function: pause()

• Pauses until the user presses a key.

Function: printHeader()

• Prints a formatted title/header for better UI.

• Source Code
#include <stdio.h>

#include <stdlib.h>

#include <string.h>
#define MAX 50

//Structure for Bus

struct Bus {

int busNo;

char source[20];

char destination[20];

char time[20];

int totalSeats;

int availableSeats;

int fare;

};

//Structure for Booking

struct Booking {

int pnr;

char name[30];

int age;

int busNo;

int seatNo;

int fare;
};

struct Bus buses[5];

intbusCount = 5;

//Function Declarations

void loadBusData();

void displayBusDetails();

void bookTicket();

int checkSeatAvailability(int busNo);

int generatePNR();

void saveBooking(struct Booking b);

void viewBookings();

void cancelTicket();

intmain() {

int choice;

loadBusData();

do {
printf("\n===== BUS TICKET BOOKING SYSTEM =====\n");

printf("1. View Bus Details\n");

printf("2. Book Ticket\n");

printf("3. View All Bookings\n");

printf("4. Cancel Ticket\n");

printf("5. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch(choice) {

case 1: displayBusDetails(); break;

case 2: bookTicket(); break;

case 3: viewBookings(); break;

case 4: cancelTicket(); break;

case 5: printf("Thank you!\n"); break;

default: printf("Invalid choice!\n");

}while(choice != 5);

return 0;

}
//Load Bus Data

void loadBusData() {

buses[0] = (struct Bus){101, "Salem", "Chennai", "6:00 AM", 40, 40, 350};

buses[1] = (struct Bus){102, "Salem", "Coimbatore", "7:30 AM", 45, 45, 300};

buses[2] = (struct Bus){103, "Salem", "Madurai", "9:00 AM", 50, 50, 400};

buses[3] = (struct Bus){104, "Salem", "Bangalore", "10:00 AM", 48, 48, 550};

buses[4] = (struct Bus){105, "Salem", "Trichy", "3:00 PM", 42, 42, 280};

//Display Buses

void displayBusDetails() {

printf("\n---- AVAILABLE BUSES ----\n");

for(int i = 0; i < busCount; i++) {

printf("\nBus No: %d", buses[i].busNo);

printf("\nRoute: %s -> %s", buses[i].source, buses[i].destination);

printf("\nTime: %s", buses[i].time);

printf("\nFare: Rs.%d", buses[i].fare);

printf("\nAvailable Seats: %d\n", buses[i].availableSeats);

}
//CheckSeat Availability

intcheckSeatAvailability(int busNo) {

for(inti= 0; i < busCount; i++) {

if(buses[i].busNo == busNo)

return buses[i].availableSeats;

return-1;

//Generate PNR

intgeneratePNR() {

return rand() % 90000 + 10000;

//Save booking to file

void saveBooking(struct Booking b) {

FILE *fp = fopen("[Link]", "a");

fprintf(fp, "%d %s %d %d %d %d\n", [Link], [Link], [Link], [Link], [Link],


[Link]);

fclose(fp);

}
//Book Ticket

voidbookTicket() {

struct Booking b;

intbusNo;

printf("\nEnter Name: ");

scanf("%s", [Link]);

printf("Enter Age: ");

scanf("%d", &[Link]);

displayBusDetails();

printf("\nEnter Bus Number to Book: ");

scanf("%d", &busNo);

intseats = checkSeatAvailability(busNo);

if(seats <= 0) {

printf("\nNo seats available in this bus!\n");

return;

}
[Link]=busNo;

[Link]=buses[busNo % busCount].totalSeats - seats + 1;

[Link]=buses[busNo % busCount].fare;

[Link]=generatePNR();

// Reduce seat

for(inti=0;i< busCount; i++) {

if(buses[i].busNo == busNo)

buses[i].availableSeats--;

saveBooking(b);

printf("\nTicket Booked Successfully!\n");

printf("PNR:%d\n", [Link]);

printf("SeatNo: %d\n", [Link]);

printf("Fare:Rs.%d\n", [Link]);

//View All Bookings


voidviewBookings() {

FILE *fp = fopen("[Link]", "r");

struct Booking b;

if(fp == NULL) {

printf("\nNo bookings available.\n");

return;

printf("\n---- ALL BOOKINGS ----\n");

while(fscanf(fp, "%d %s %d %d %d %d", &[Link], [Link], &[Link], &[Link],


&[Link], &[Link]) != EOF) {

printf("\nPNR: %d", [Link]);

printf("\nName: %s", [Link]);

printf("\nAge: %d", [Link]);

printf("\nBus No.: %d", [Link]);

printf("\nSeat No: %d", [Link]);

printf("\nFare: Rs.%d\n", [Link]);

fclose(fp);

}
//Cancel Ticket

void cancelTicket() {

int pnr;

printf("\nEnter PNR to Cancel: ");

scanf("%d", &pnr);

FILE *fp = fopen("[Link]", "r");

FILE *temp = fopen("[Link]", "w");

struct Booking b;

int found = 0;

while(fscanf(fp,"%d%s %d %d %d %d", &[Link], [Link], &[Link], &[Link],


&[Link],&[Link])!=EOF) {

if([Link]== pnr) {

found= 1;

//Increaseseatcount

for(inti=0;i<busCount; i++) {

if(buses[i].busNo == [Link])

buses[i].availableSeats++;
}

printf("\nTicket Cancelled Successfully!\n");

}else {

fprintf(temp, "%d %s %d %d %d %d\n", [Link], [Link], [Link], [Link],


[Link], [Link]);

fclose(fp);

fclose(temp);

remove("[Link]"); rename("[Link]", "[Link]");

if(!found) printf("\nPNR not found!\n");}

✅ Testing – Bus Ticket Booking System (C Programming)

1. Introduction to Testing
Testing ensures that the Bus Ticket Booking System works correctly, handles user
inputs properly, and produces the expected output without errors. The following test
cases verify the core functions such as booking, cancellation, searching, and file
handling.
2. Test Cases
Test Case 1 – View Bus Details

Test Case ID TC01

Description Displaylistofavailable buses

Input Select option 1 from menu

Expected Bus No, Route, Time, Fare, Available Seats displayed


Output

Result Pass

Test Case 2 – Book Ticket (Valid Input)

Test Case ID TC02


Description User books a ticket successfully
Input Name, Age, Valid Bus No
Expected Ticket booked, PNR generated, seat
Output reduced
Result Pass

Test Case 3 – Book Ticket (Invalid Bus No)

Test Case ID TC03


Description Invalid bus number input
Input Bus No = 999
Expected “No seats available / Invalid bus
Output number”
Result Pass

Test Case 4 – View All Bookings

Test Case ID TC04


Description Display all saved bookings
Input Select option 3
Expected Shows PNR, Name, Age, Bus No, Seat
Output No, Fare
Result Pass

Test Case 5 – Cancel Ticket (Valid PNR)

Test Case ID TC05


Description Cancel an existing ticket
Input Valid PNR number
Expected “Ticket Cancelled Successfully” + seat
Output increased
Result Pass

Test Case 6 – Cancel Ticket (Invalid PNR)

Test Case ID TC06


Description Cancel using PNR not
Input in file
Expected PNR = 00000
Output “PNR Not Found”
Result Pass
Test Case 7 – File Handling Test

Test Case ID TC07


Description Check whether booking is
Input saved in file
Expected Book ticket
Output Data should be written to
Result [Link]
Pass

Future Scope / Enhancements

The Bus Ticket Booking System can be improved and expanded with the following
enhancements:

1. Online Payment Integration

• Add UPI, credit/debit card, and net banking options.


• Automatically generate digital receipts.

2. Real-Time Seat Availability

• Live seat updates using a database.


• Prevents double-booking during simultaneous access.

3. User Login System

• Separate login for admin and passengers.


• Allows users to view their booking history securely.
4. Admin Dashboard

• Add, modify, or delete bus routes.


• Manage fares, timings, and seat capacity easily.

5. Mobile App Integration

• Create Android/iOS application for easy ticket booking.


• Allows notifications for booking confirmation and journey reminders.

6. QR Code Tickets

• Generate QR code for each ticket.


• Enable quick verification during boarding.

7. Database Integration (MySQL/SQLite)

• Replace text file storage with a database.


• Supports large data, multiple users, and faster search.

8. GPS-Based Bus Tracking

• Real-time bus location tracking.


• Notify users about arrival time or delay.
9. Multi-Language Support

• Support for Tamil, Hindi, Malayalam, Telugu, etc.


• Useful for diverse users.

10. Refund & Wallet System

• Automatic refund calculation.


• Add wallet balance for future booking

✅ Conclusion

The Bus Ticket Booking System developed using C programming successfully


demonstrates how basic programming concepts can be applied to solve real-life
problems. The system allows users to view buses, book tickets, check seat
availability, and cancel bookings efficiently. Through the use of structures, file
handling, functions, and decision-making statements, the project achieves a smooth
and user-friendly process for managing ticket reservations.
Although the system runs in a console environment, it provides a clear understanding
of how ticket automation works in real transport services. This project also lays the
foundation for future enhancements such as online payments, database connectivity,
and mobile app integration. Overall, the project meets its objectives and helps
improve understanding of practical C programming implementation.

✅ References

1. Yashavant Kanetkar, Let Us C, BPB Publications – Concepts of C


programming, functions, and file handling.
2. E. Balagurusamy, Programming in ANSI C, McGraw Hill – Structures,
arrays, and modular programming concepts.
3. Byron Gottfried, Schaum’s Outline of Programming with C, McGraw Hill –

Problem-solving methods using C.

– C Basics
4. TutorialsPoint Programming
Section
(Syntax, functions, loops, file handling examples)
– C
5. GeeksforGeeks Programming
Overflow
(Reference for logical implementation and program structure)

6. Stack
(Used for troubleshooting coding errors and best practices)

💻 C Program: Bus Ticket Booking System

This program allows a user to book, view, and check the status of bus seats.

C
#include #include #include #include <stdio.h>
<conio.h>
// #define <stdlib.h>
<string.h>
bus
Define the maximum number of seats on the
40
MAX_SEATS
// Define the filename for storing booking data
#define FILENAME "bus_bookings.dat"
details
// Structure to hold passenger
{
struct bus_booking
seat_num;
int
name[50];
char
mobile[15];
char
destination[50];
char
};

// Global array to represent the seats on the bus (0=Available,


1=Booked)
int seat_status[MAX_SEATS] = {0};

// Function prototypes
void menu();
void display_seats();
void book_ticket();
void view_bookings();
void load_data();
void save_data();

// Main function
int main() {
load_data(); // Load existing data from file at startup
menu();
return 0;
}

// Function to display the main menu


void menu() {
int choice;
do {
system("cls"); // Clear screen (for Windows; use
"clear" for Linux/macOS)

printf("\n\t\t==========================================");
printf("\n\t\t\tBUS TICKET BOOKING SYSTEM ");

printf("\n\t\t==========================================");
printf("\n\n\t[1] Display Bus Seat Status");
printf("\n\t[2] Book Ticket");
printf("\n\t[3] View All Bookings");
printf("\n\t[4] Exit Program");
printf("\n\n\tEnter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
display_seats();
break;
case 2:
book_ticket();
break;
case 3:
view_bookings();
break;
case 4:
save_data(); // Save data before exiting
printf("\n\tThank you for using the system.
Data saved successfully!\n");
printf("\tPress any key to exit...");
getch();
exit(0);
default:
printf("\n\tInvalid choice. Please try
again.");
getch();
}
} while (choice != 4);
}
// Function to load existing booking data from the file
{
void load_data()
*fp;
FILE
booking;
struct bus_booking
initially
// Reset all seat statuses to available {
for (int i = 0; i < MAX_SEATS; i++) 0;
seat_status[i] =
}

fp = fopen(FILENAME, "rb");
if (fp == NULL) {
// File does not exist, or is empty. Initializing an
empty file.
// printf("Booking file not found. Starting
fresh.\n"); // Debug message
return;
}

// Read all records and update seat_status array


while (fread(&booking, sizeof(struct bus_booking), 1, fp)
== 1) {
if (booking.seat_num >= 1 && booking.seat_num <=
MAX_SEATS) {
seat_status[booking.seat_num - 1] = 1; // Mark
seat as booked
}
}
fclose(fp);
}

// Function to save all existing bookings (and potentially the


seat status) to the file
void save_data() {
a
// In this simple model, save_data is effectively just
load_data check
// combined with the writes done in book_ticket.
// The main purpose of this is to ensure data persistence.
// The load_data/book_ticket combination handles the
saving process for us.
// We only need to call load_data() at the beginning and
book_ticket() handles
// appending new records, which is sufficient for this
simple system.
}

// Function to display the current seat map


void display_seats() {
system("cls");
printf("\n\t\t\tBUS SEAT STATUS (Bus No: 101, Route: City
A to City B)\n");

printf("\t==================================================
======================\n");
printf("\t\t\t\t[ A ] = Available, [ B ] = Booked\n");

printf("\t==================================================
======================\n\n");

for (int i = 0; i < MAX_SEATS; i++) {


printf(" [%c] %02d", (seat_status[i] == 0 ? 'A' :
'B'), i + 1);
if ((i + 1) % 4 == 0) { // New line after every 4
seats
printf("\n");
} else if ((i + 1) % 2 == 0) { // Extra space after
every 2 seats (aisle)
printf(" | ");
}
}
printf("\n\n\tPress any key to return to the menu...");
getch();
}

// Function to book a ticket


void book_ticket() {
system("cls");
display_seats();
printf("\n\t====================== TICKET BOOKING
======================\n");

int seat_num;
printf("\n\tEnter Seat Number to book (1-%d): ",
MAX_SEATS);
scanf("%d", &seat_num);
number
// Validate seat {
if (seat_num < 1 || seat_num > MAX_SEATS)
printf("\n\tInvalid seat number. Press any key to
continue...");
getch();
return;
}

// Check if the seat is already booked


if (seat_status[seat_num - 1] == 1) {
printf("\n\tSeat %d is already booked. Please choose
an available seat.", seat_num);
getch();
return;
}

// Seat is available, proceed with booking


struct bus_booking new_booking;
new_booking.seat_num = seat_num;

printf("\tEnter Passenger Name: ");


fflush(stdin); // Clear the input buffer
gets(new_booking.name); // Using gets is risky, but common
in simple C projects
");
printf("\tEnter Mobile Number:
gets(new_booking.mobile);

printf("\tEnter Destination: ");


gets(new_booking.destination);

// Write the new booking record to the file


FILE *fp = fopen(FILENAME, "ab"); // Append in binary mode
if (fp == NULL) {
printf("\n\tError opening file for writing.");
getch();
return;
}

if (fwrite(&new_booking, sizeof(struct bus_booking), 1,


fp) != 1) {
printf("\n\tError writing record to file.");
getch();
fclose(fp);
return;
}
fclose(fp);
seat_status[seat_num - 1] = 1; // Update the in-memory
status

printf("\n\t================================================
==");
printf("\n\tBOOKING SUCCESSFUL! Seat %d is booked for %s.",
seat_num, new_booking.name);

printf("\n\t================================================
==");
printf("\n\tPress any key to return to the menu...");
getch();
}

// Function to view all booking records


void view_bookings() {
system("cls");
FILE *fp;
struct bus_booking booking;
int count = 0;

printf("\n\t\t\t\t\tALL BOOKING RECORDS\n");

printf("\t==================================================
======================\n");
printf("\tSeat | Passenger Name\t| Mobile Number\t|
Destination\n");
printf("\t----------------------------------------------
--------------------------\n");

fp = fopen(FILENAME, "rb"); // Read in binary mode


if (fp == NULL) {
printf("\n\tNo bookings found yet.");
printf("\n\tPress any key to return to the menu...");
getch();
return;
}

// Read all records and print them


while(fread(&booking, sizeof(struct bus_booking), 1, fp)
== 1) {
printf("\t%4d | %-20s| %-14s| %s\n",
booking.seat_num,
[Link],
[Link],
[Link]);
count++;
}

fclose(fp);

if (count == 0) {
printf("\n\tNo bookings found yet.");
}

printf("\t----------------------------------------------
--------------------------\n");
printf("\n\tTotal Bookings: %d", count);
printf("\n\tPress any key to return to the menu...");
getch();
}

🖥️ Sample Program Output

Here is a step-by-step example of how the program would run, assuming the system
starts with no existing bookings.
Step 1: Main Menu

==========================================
BUS TICKET BOOKING SYSTEM
==========================================

[1] Display Bus Seat Status


[2] Book Ticket
[3] View All Bookings
[4] Exit Program
Enter 1
your choice:
Step 2: Initial Seat Status (Choice 1)

BUS SEAT STATUS (Bus No: 101, Route: City A to City B)

===========================================================
=============
[ A ] = Available, [ B ] = Booked

===========================================================
=============
|
[A] 01 [A] 02 [A] 03 | [A] 04
|
| [A] 05 [A] 06 [A] 07 | [A] 08
[A] 09 [A] 10 [A] 11 | [A] 12
... (All 40 seats are [A] Available)
to menu...
Press any key return to the

Step 3: Booking a Ticket (Choice 2)


(Return to Menu and enter '2')

BUS SEAT STATUS (Bus No: 101, Route: City A to City B)


... (Displays the seat map again)
====================== TICKET BOOKING
======================

Enter Seat Number to book (1-40): 10


Enter Passenger Name: Rahul Sharma
Enter Mobile Number: 9876543210
Enter Destination: Mumbai

==================================================
BOOKING SUCCESSFUL! Seat 10 is booked for Rahul Sharma.
==================================================
Press any key to return to the menu...

Step 4: Displaying the Updated Status (Choice 1)


(Return to Menu and enter '1' again)

BUS SEAT STATUS (Bus No: 101, Route: City A to City B)

===========================================================
=============
[ A ] = Available, [ B ] = Booked

===========================================================
=============
|
[A] 01 [A] 02 [A] 03 | [A] 04
|
[A] 05 [A] 06 [A] 07 | [A] 08
[A] 09 | [B] 10 [A] 11 | [A] 12 <-- Seat 10 is now [B] Booked
...

Step 5: Viewing All Bookings (Choice 3)


(Return to Menu and enter '3')

ALL BOOKING RECORDS

=============== =========== == =============== ========


=====================
Seat | Passenger Name | Mobile Number | Destination
------------------------------------------------------------------------
10 | Rahul Sharma | 9876543210 | Mumbai
------------------------------------------------------------------------

Total Bookings: 1
Press any key to return to the menu...

Step 6: Exiting the Program (Choice 4)


(Return to Menu and enter '4')

Thank you for using the system. Data saved successfully!


Press any key to exit...

You might also like