111 lines
1.9 KiB
C
111 lines
1.9 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;
|
|
|
|
static char names[MAX_NAMES][MAX_NAME_LEN+1];
|
|
static unsigned int numberOfEntries = 0;
|
|
|
|
int addName(const char *name)
|
|
{
|
|
if(numberOfEntries < MAX_NAMES)
|
|
{
|
|
strncpy(names[numberOfEntries], name, MAX_NAME_LEN+1);
|
|
names[numberOfEntries][MAX_NAME_LEN] = '\0';
|
|
numberOfEntries++;
|
|
return 1;
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
void printNames()
|
|
{
|
|
for(int i = 0; i < numberOfEntries; i++)
|
|
{
|
|
printf("%s\n", names[i]);
|
|
}
|
|
}
|
|
|
|
static int getNameIdx(const char *name)
|
|
{
|
|
for(int i = 0; i < numberOfEntries; i++)
|
|
{
|
|
if(strcmp(name, names[i]) == 0)
|
|
return i;
|
|
}
|
|
return INDEX_NOT_FOUND;
|
|
}
|
|
|
|
static void removeAt(int idx)
|
|
{
|
|
for(int i = idx; i < numberOfEntries-1; i++)
|
|
{
|
|
strncpy(names[i], names[i+1], MAX_NAME_LEN+1);
|
|
names[i][MAX_NAME_LEN] = '\0';
|
|
}
|
|
numberOfEntries--;
|
|
}
|
|
|
|
Status removeName(const char *name)
|
|
{
|
|
int idx = getNameIdx(name);
|
|
|
|
if(idx == INDEX_NOT_FOUND)
|
|
{
|
|
return REMOVE_ERROR;
|
|
}
|
|
else
|
|
{
|
|
removeAt(idx);
|
|
return STATUS_OK;
|
|
}
|
|
}
|
|
|
|
Status saveNames(const char *path)
|
|
{
|
|
FILE *file = fopen(path, "w");
|
|
|
|
if(file != NULL)
|
|
{
|
|
for(int i = 0; i < numberOfEntries; i++)
|
|
fprintf(file, "%s\n", names[i]);
|
|
fclose(file);
|
|
|
|
return STATUS_OK;
|
|
}
|
|
else
|
|
{
|
|
return IO_ERROR;
|
|
}
|
|
}
|
|
|
|
Status loadNames(const char *path)
|
|
{
|
|
FILE *file = fopen(path, "r");
|
|
|
|
if(file != NULL)
|
|
{
|
|
char line[MAX_NAME_LEN+10];
|
|
|
|
while(fgets(line, MAX_NAME_LEN+10, file) != NULL)
|
|
{
|
|
line[strcspn(line, "\n")] = '\0';
|
|
addName(line);
|
|
}
|
|
|
|
return STATUS_OK;
|
|
}
|
|
else
|
|
{
|
|
return IO_ERROR;
|
|
}
|
|
} |