diff options
author | Your Name <admin@zero.net> | 2025-04-30 11:53:44 +0200 |
---|---|---|
committer | Your Name <admin@zero.net> | 2025-04-30 11:53:44 +0200 |
commit | 0efd01a956e0f524f3c084548b314f40f6831441 (patch) | |
tree | 35a464f15151afa6d7b34a46d005950fa7a222b9 /chatroom.c |
base project
Diffstat (limited to 'chatroom.c')
-rw-r--r-- | chatroom.c | 65 |
1 files changed, 65 insertions, 0 deletions
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 <stdio.h> +#include <stdlib.h> +#include <string.h> + +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, ""); +} |