edit.c (2955B)
1 #include <stdio.h> 2 #include <string.h> 3 #include <stdlib.h> 4 5 #include "util.h" 6 #include "post.h" 7 8 #define DELIMITER "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n" 9 10 int edit_read(char *filename, post_t **post) { 11 char *content = util_read_file(filename); 12 int len = strlen(content); 13 int delimiter_start = 0; 14 for (int i = 0; i < len; i++) { 15 if (strncmp(content + i, DELIMITER, strlen(DELIMITER)) == 0) { 16 delimiter_start = i; 17 break; 18 } 19 } 20 int delimiter_end = delimiter_start + strlen(DELIMITER); 21 char head[delimiter_start + 1]; 22 memcpy(head, content, delimiter_start); 23 head[delimiter_start] = '\0'; 24 char *body = malloc(sizeof(char) * (len - delimiter_end + 1)); 25 memcpy(body, content + delimiter_end, len - delimiter_end); 26 body[len - delimiter_end] = '\0'; 27 free(content); 28 *post = malloc(sizeof(post_t)); 29 post_init(*post); 30 int line_nr = 0; 31 int line_start = 0; 32 for (int i = 0; i < (int) strlen(head); i++) { 33 char c = head[i]; 34 if (c == '\n') { 35 int line_end = i; 36 if (i > 0 && head[i - 1] == '\r') { 37 line_end--; 38 } 39 char *line = malloc(sizeof(char) * (line_end - line_start + 1)); 40 memcpy(line, head + line_start, line_end - line_start); 41 line[line_end - line_start] = '\0'; 42 switch (line_nr) { 43 case 0: { 44 (*post)->label = line; 45 break; 46 } 47 case 1: { 48 (*post)->title = line; 49 break; 50 } 51 case 2: { 52 (*post)->summary = line; 53 break; 54 } 55 case 3: { 56 if (strcmp(line, "true") == 0) { 57 (*post)->is_public = malloc(sizeof(bool)); 58 *(*post)->is_public = true; 59 } 60 else { 61 (*post)->is_public = malloc(sizeof(bool)); 62 *(*post)->is_public = false; 63 } 64 free(line); 65 break; 66 } 67 default: 68 free(line); 69 break; 70 } 71 line_start = i + 1; 72 line_nr++; 73 } 74 } 75 (*post)->content = body; 76 remove(filename); 77 return 0; 78 } 79 80 int edit_write(char *filename, post_t *post) { 81 FILE *fp = fopen(filename, "aw+"); 82 char label[500]; 83 snprintf(label, 500, "%s\r\n", post->label); 84 fwrite(label, sizeof(char), strlen(label), fp); 85 char title[500]; 86 snprintf(title, 500, "%s\r\n", post->title); 87 fwrite(title, sizeof(char), strlen(title), fp); 88 char summary[500]; 89 snprintf(summary, 500, "%s\r\n", post->summary); 90 fwrite(summary, sizeof(char), strlen(summary), fp); 91 char is_public[500]; 92 snprintf(is_public, 500, "%s\r\n", *post->is_public ? "true" : "false"); 93 fwrite(is_public, sizeof(char), strlen(is_public), fp); 94 fwrite(DELIMITER, sizeof(char), strlen(DELIMITER), fp); 95 int content_len = strlen(post->content) + 2; 96 char content[content_len]; 97 snprintf(content, content_len, "%s", post->content); 98 fwrite(content, sizeof(char), strlen(content), fp); 99 fclose(fp); 100 return 0; 101 }