From 0efd01a956e0f524f3c084548b314f40f6831441 Mon Sep 17 00:00:00 2001 From: Your Name Date: Wed, 30 Apr 2025 11:53:44 +0200 Subject: base project --- chatroom.c | 65 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 chatroom.c (limited to 'chatroom.c') diff --git a/chatroom.c b/chatroom.c new file mode 100644 index 0000000..e2a6b1a --- /dev/null +++ b/chatroom.c @@ -0,0 +1,65 @@ +#include "client.h" +#include "chatroom.h" +#include +#include +#include + +chatroom_t chatrooms[MAX_CHATROOMS]; +int chatroom_count = 0; + +void load_chatrooms(const char *filename) { + FILE *fp = fopen(filename, "r"); + if (!fp) { + perror("chatroom file"); + exit(1); + } + + while (fscanf(fp, "%s %d %s %s %[^\n]", + chatrooms[chatroom_count].name, + &chatrooms[chatroom_count].users, + chatrooms[chatroom_count].created, + chatrooms[chatroom_count].time, + chatrooms[chatroom_count].topic) == 5) { + chatroom_count++; + } + + fclose(fp); +} + +void print_chatroom_list(int sock) { + send_to_client(sock, "room-name # created time topic\n"); + send_to_client(sock, "--------------------------------------------------------\n"); + for (int i = 0; i < chatroom_count; i++) { + char line[BUFFER_SIZE]; + snprintf(line, sizeof(line), "%-10s %-4d %-12s %-8s %s\n", + chatrooms[i].name, + chatrooms[i].users, + chatrooms[i].created, + chatrooms[i].time, + chatrooms[i].topic); + send_to_client(sock, line); + } + send_to_client(sock, "--------------------------------------------------------\n"); +} + +int join_chatroom(const char *name, client_t *cli) { + for (int i = 0; i < chatroom_count; i++) { + if (strcmp(chatrooms[i].name, name) == 0) { + leave_chatroom(cli); + strncpy(cli->room, name, sizeof(cli->room) - 1); + chatrooms[i].users++; + return 1; + } + } + return 0; +} + +void leave_chatroom(client_t *cli) { + for (int i = 0; i < chatroom_count; i++) { + if (strcmp(chatrooms[i].name, cli->room) == 0) { + chatrooms[i].users--; + break; + } + } + strcpy(cli->room, ""); +} -- cgit v1.2.3