StudyPlanner/src/db.c

105 lines
3.0 KiB
C

/* Create a database and handel it
* Created by Jan on 13.12.2024.
* INPUT: query for previous state
* linked list of tasks to store
*
* OUTPUT:
* linked list of tasks from file
* OK
*
*
*/
#include "llist.h"
#include "planner.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
/*
write a complete linkedlist to a task csv file.
*/
void write_linkedlist_to_csv(llist *head, const char *filename) {
// Open file with write permision
FILE *file = fopen(filename, "w");
// if there is no file or a wrong file path you becom an error
if (file == NULL) {
fprintf(stderr, "Could not open file %s\n", filename);
exit(1);
} else {
// write the file header
fprintf(file, "TaskName, Created, Deadline, Priority, Spare\n");
// Iterate through the linked list and write the data to the CSV
llist *current = head;
Task *task;
while (current != NULL) {
task = current->data;
// Write the task data to the CSV file
fprintf(file, "%s, %llu, %llu, %d, %llu\n", task->name, task->created,
task->deadline, task->priority, task->spare);
current = current->next;
}
fclose(file); // Close the file
}
}
/*
read a task csv file and write the data in a linked list
*/
llist *write_csv_to_llist(const char *filename) {
llist *list = NULL; // list to return
// Open file with read permision
FILE *file = fopen(filename, "r");
if (file == NULL) {
fprintf(stderr, "Could not open file %s\n", filename);
} else {
char line[1024]; // Line Buffer
int count = 0; // task counter
fgets(line, sizeof(line), file); // read and ignore file head
while (fgets(line, sizeof(line), file)) {
memset(line, 0, sizeof(line));
count++;
// remove newline sign
line[strcspn(line, "\n")] = '\0';
// column slice
char *taskname = strtok(line, ",");
char *taskcreation_dateSTR = strtok(NULL, ",");
char *taskdeadline_dateSTR = strtok(NULL, ",");
char *taskprioritySTR = strtok(NULL, ",");
char *taskspareSTR = strtok(NULL, ",");
printf(" Der Name des Task ist %s\n",taskname);
// convert char in integer and date
unsigned long int taskcreation_date =
strtoul(taskcreation_dateSTR, NULL, 10);
unsigned long int taskdeadline_date =
strtoul(taskdeadline_dateSTR, NULL, 10);
unsigned long int taskspare = strtoul(taskspareSTR, NULL, 10);
int priority = atoi(taskprioritySTR);
// create Task
Task *task = newTask(taskname, taskcreation_date, taskdeadline_date,
priority, taskspare);
// Insert task into the linked list
if (list == NULL) {
// If the list is empty, initialize it with the first task
list = llistNew(task, cmpTaskN);
} else {
// Append the task to the linked list
llistAppend(list, task);
}
}
fclose(file);
}
return list; // null on error
}