aboutsummaryrefslogtreecommitdiff
path: root/common.c
diff options
context:
space:
mode:
authorRaymaekers Luca <raymaekers.luca@gmail.com>2024-10-19 15:31:51 +0200
committerRaymaekers Luca <raymaekers.luca@gmail.com>2024-10-19 15:31:51 +0200
commitff0aae89238f4d60267def24476e8b9f4cb596cf (patch)
treed8a646d04c0e2617bf279b387e5d11960906d340 /common.c
parent104dabefd62952f2d892a2dcdfb5700d9379ac00 (diff)
add serialization to file code
Diffstat (limited to 'common.c')
-rw-r--r--common.c59
1 files changed, 58 insertions, 1 deletions
diff --git a/common.c b/common.c
index b177987..d72ead3 100644
--- a/common.c
+++ b/common.c
@@ -1,9 +1,12 @@
+#include "common.h"
#include "config.h"
+
#include <stdarg.h>
+#include <stdint.h>
+#include <stdio.h>
#include <strings.h>
#include <unistd.h>
-// wrapper for write
void writef(char *format, ...)
{
va_list args;
@@ -18,3 +21,57 @@ void writef(char *format, ...)
n++;
write(0, buf, n);
}
+
+u16 str_len(char *str)
+{
+ u16 i = 0;
+ while (str[i])
+ i++;
+ return i;
+}
+
+void str_cpy(char *to, char *from)
+{
+ while ((*to++ = *from++))
+ ;
+}
+
+u8 save_message(struct message *msg, FILE *f)
+{
+ u8 err = 0;
+ u16 len;
+ if (msg->text == NULL) {
+ len = 0;
+ msg->text = ""; // TODO: Error empty message should not be allowed.
+ } else {
+ len = str_len(msg->text);
+ }
+
+ if (len == 0)
+ err = 1;
+
+ fwrite(&msg->timestamp, sizeof(*msg->timestamp) * MSG_TIMESTAMP_LEN, 1, f);
+ fwrite(&msg->author, sizeof(*msg->author) * MSG_AUTHOR_LEN, 1, f);
+ fwrite(&len, sizeof(len), 1, f);
+ fputs(msg->text, f);
+
+ return err;
+}
+
+u8 load_message(struct message *msg, FILE *f)
+{
+ fread(msg, sizeof(*msg->timestamp) * MSG_TIMESTAMP_LEN + sizeof(*msg->author) * MSG_AUTHOR_LEN, 1, f);
+ u16 len;
+ fread(&len, sizeof(len), 1, f);
+ if (len == 0) {
+ // TODO: Error: empty message should not be allowed
+ // empty message
+ msg->text = "";
+ return 1;
+ }
+ char txt[len];
+ fgets(txt, len, f);
+ msg->text = txt;
+
+ return 0;
+}