edit.c (2761B)
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)->title = line; 45 break; 46 } 47 case 1: { 48 (*post)->summary = line; 49 break; 50 } 51 case 2: { 52 if (strcmp(line, "true") == 0) { 53 (*post)->is_public = malloc(sizeof(bool)); 54 *(*post)->is_public = true; 55 } 56 else { 57 (*post)->is_public = malloc(sizeof(bool)); 58 *(*post)->is_public = false; 59 } 60 free(line); 61 break; 62 } 63 default: 64 free(line); 65 break; 66 } 67 line_start = i + 1; 68 line_nr++; 69 } 70 } 71 (*post)->content = body; 72 remove(filename); 73 return 0; 74 } 75 76 int edit_write(char *filename, post_t *post) { 77 FILE *fp = fopen(filename, "aw+"); 78 char title[500]; 79 snprintf(title, 500, "%s\r\n", post->title); 80 fwrite(title, sizeof(char), strlen(title), fp); 81 char summary[500]; 82 snprintf(summary, 500, "%s\r\n", post->summary); 83 fwrite(summary, sizeof(char), strlen(summary), fp); 84 char is_public[500]; 85 snprintf(is_public, 500, "%s\r\n", *post->is_public ? "true" : "false"); 86 fwrite(is_public, sizeof(char), strlen(is_public), fp); 87 fwrite(DELIMITER, sizeof(char), strlen(DELIMITER), fp); 88 int content_len = strlen(post->content) + 2; 89 char content[content_len]; 90 snprintf(content, content_len, "%s", post->content); 91 fwrite(content, sizeof(char), strlen(content), fp); 92 fclose(fp); 93 return 0; 94 }