djumbai/test/message_cli.c
2024-05-12 21:15:06 +01:00

132 lines
3.6 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
void displayHeader() {
printf("╭━━━╮╱╱╱╱╱╱╭╮\n");
printf("╰╮╭╮┣╮╱╱╱╱╱┃┃\n");
printf("╱┃┃┃┣╋╮╭┳╮╭┫╰━┳━━┳╮\n");
printf("╱┃┃┃┣┫┃┃┃╰╯┃╭╮┃╭╮┣┫\n");
printf("╭╯╰╯┃┃╰╯┃┃┃┃╰╯┃╭╮┃┃\n");
printf("╰━━━┫┣━━┻┻┻┻━━┻╯╰┻╯\n");
printf("╱╱╱╭╯┃\n");
printf("╱╱╱╰━╯\n");
}
void displayAllMessages(uid_t userID) {
char dirname[256];
sprintf(dirname, "%d", userID); // Convert userID to string
DIR *dir;
struct dirent *entry;
printf("Reading all messages for UserID %d...\n", userID);
dir = opendir(dirname);
if (dir == NULL) {
printf("Error opening directory\n");
return;
}
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_REG) { // If it's a regular file
displayMessage(dirname, entry->d_name);
}
}
closedir(dir);
}
void displayUserMessages(char *userID) {
char currentUserDir[256];
sprintf(currentUserDir, "%d", getuid()); // Convert currentUserID to string
char userDir[256];
sprintf(userDir, "%s/%s", currentUserDir, userID); // Construct user directory path
DIR *dir;
struct dirent *entry;
printf("Reading messages from user %s...\n", userID);
dir = opendir(userDir);
if (dir == NULL) {
printf("Error opening directory for user %s\n", userID);
return;
}
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_REG) { // If it's a regular file
displayMessage(userDir, entry->d_name);
}
}
closedir(dir);
}
void displayGroupMessages(char *groupID) {
printf("Reading messages from group %s...\n", groupID);
// Your code to read messages from a specific group
}
void displayMessage(char *dirname, char *filename) {
char filepath[256];
sprintf(filepath, "%s/%s", dirname, filename);
FILE *file = fopen(filepath, "r");
if (file == NULL) {
printf("Error opening file: %s\n", filename);
return;
}
printf("----- %s -----\n", filename);
char buffer[256];
while (fgets(buffer, sizeof(buffer), file)) {
printf("%s", buffer);
}
printf("\n----- End of %s -----\n", filename);
fclose(file);
}
int main() {
int choice;
char userID[20];
char groupID[20];
displayHeader();
while(1) {
printf("\nCurrent UserID: %d\n", getuid());
printf("Options:\n");
printf("1. all (read all messages)\n");
printf("2. user -userID_here (read messages from given userID)\n");
printf("3. group -groupID_here\n");
printf("4. kill (exit the program)\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch(choice) {
case 1:
displayAllMessages(getuid());
break;
case 2:
printf("Enter userID: ");
scanf("%s", userID);
displayUserMessages(userID);
break;
case 3:
printf("Enter groupID: ");
scanf("%s", groupID);
displayGroupMessages(groupID);
break;
case 4:
printf("Exiting program...\n");
exit(0);
default:
printf("Invalid choice. Please try again.\n");
}
}
return 0;
}