2025-10-30 13:22:22 +01:00

89 lines
1.7 KiB
C

#include "namesarchive.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define INDEX_NOT_FOUND -1
typedef struct
{
char name[MAX_NAME_LEN+1];
unsigned int id;
} Student;
Student students[MAX_NAMES];
unsigned int numberOfEntries = 0;
int addStudent(const char *name, unsigned int id)
{
if(numberOfEntries < MAX_NAMES)
{
strncpy(students[numberOfEntries].name, name, MAX_NAME_LEN+1);
students[numberOfEntries].name[MAX_NAME_LEN] = '\0';
students[numberOfEntries].id = id;
numberOfEntries++;
return 1;
}
return 0;
}
void printStudents()
{
for(int i = 0; i < numberOfEntries; i++)
{
printf("%s: %u\n", students[i].name, students[i].id);
}
}
static int getNameIdx(const char *name)
{
for(int i = 0; i < numberOfEntries; i++)
{
if(strcmp(name, students[i].name) == 0)
return i;
}
return INDEX_NOT_FOUND;
}
static void removeAt(int idx)
{
for(int i = idx; i < numberOfEntries-1; i++)
{
students[i] = students[i+1];
}
numberOfEntries--;
}
Status removeStudent(const char *name)
{
int idx = getNameIdx(name);
if(idx == INDEX_NOT_FOUND)
{
return REMOVE_ERROR;
}
else
{
removeAt(idx);
return STATUS_OK;
}
}
static int compareStudents(const void *arg1, const void *arg2)
{
const Student *student1 = (const Student *)arg1;
const Student *student2 = (const Student *)arg2;
int nameDiff = strcmp(student1->name, student2->name);
if(nameDiff == 0)
return student1->id - student2->id;
else
return nameDiff;
}
void sortStudents()
{
qsort(students, numberOfEntries, sizeof(Student), compareStudents);
}