So I'm implementing a TCP server chatroom in C and using poll to handle multiple clients. Users register with a username and password and then Login with it. When they login I want to add them to this struct array.
struct onlineUsers{
int sockfd;
char username[9]; //usernames size is maximum 8 characters
};
struct onlineUsers users[10];
//The login function is pretty long so is here the relevant part.
if(!searchExist(search, db)){
printf("Account doesnt exist.\n");
fclose(db);
free(search);
return -1;
}
else{
printf("Logged in\n");
// Add to onlineUser struct arr[]
}
But when the client closes the connection how would you remove that specific element from the onlineUsers array? I haven't implemented the way to add them since I don't really have a good way to remove them.
CodePudding user response:
I reworked this into a minimal example and implemented a linear search for you (use lfind
in remove_user()
and lsearch
in add_user()
if available):
#include <assert.h>
#include <string.h>
#define MAX_NAME 8
#define MAX_USERS 2
struct user {
char name[MAX_NAME 1];
};
unsigned find_pos(struct user *users, const char *name) {
unsigned empty = MAX_USERS;
for(unsigned i = 0; i < MAX_USERS; i ) {
if(empty == MAX_USERS && !users[i].name[0]) empty = i;
if(!strcmp(users[i].name, name)) return i;
}
return empty;
}
int add_user(struct user *users, const char *name) {
unsigned pos = find_pos(users, name);
if(pos == MAX_USERS) return -1;
if(users[pos].name[0]) return 1;
// safe as name[8] is 0 initialized; otherwise
// copy MAX_NAME 1 then set name[MAX_NAME] = '\0'
// to ensure string is \0 terminated.
strncpy(users[pos].name, name, MAX_NAME);
return 0;
}
int remove_user(struct user *users, const char *name) {
int pos = find_pos(users, name);
if(!users[pos].name[0] || strcmp(users[pos].name, name)) return 1;
users[pos].name[0] = '\0';
return 0;
}
int main() {
struct user users[MAX_USERS] = { 0 };
assert(add_user(users, "bob") == 0); // ok (1 of 2)
assert(add_user(users, "bob") == 1); // duplicate
assert(remove_user(users, "bob") == 0); // ok (empty)
assert(remove_user(users, "jane") == 1); // non-existing
assert(add_user(users, "bob") == 0); // ok (1 of 2)
assert(add_user(users, "jane") == 0); // ok (2 of 2)
assert(add_user(users, "jack") == -1); // full
assert(remove_user(users, "bob") == 0); // ok
assert(find_pos(users, "jane") == 1); // ok (not empty slot)
}