|
| 1 | +/* |
| 2 | +** EPITECH PROJECT, 2025 |
| 3 | +** __ |
| 4 | +** File description: |
| 5 | +** _ |
| 6 | +*/ |
| 7 | + |
| 8 | +#include <fcntl.h> |
| 9 | +#include <stdio.h> |
| 10 | +#include <unistd.h> |
| 11 | + |
| 12 | +#include "dataframe.h" |
| 13 | + |
| 14 | +static |
| 15 | +void write_value(void *vl, FILE *file, column_type_t type, char *col_name) |
| 16 | +{ |
| 17 | + fprintf(file, " \"%s\": ", col_name); |
| 18 | + switch (type) { |
| 19 | + case INT: |
| 20 | + fprintf(file, "%d", *(int *)vl); |
| 21 | + break; |
| 22 | + case UINT: |
| 23 | + fprintf(file, "%u", *(uint32_t *)vl); |
| 24 | + break; |
| 25 | + case FLOAT: |
| 26 | + fprintf(file, "%.2f", *(float *)vl); |
| 27 | + break; |
| 28 | + case BOOL: |
| 29 | + case STRING: |
| 30 | + fprintf(file, "\"%s\"", (char *)vl); |
| 31 | + break; |
| 32 | + default: |
| 33 | + return; |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +static |
| 38 | +void write_values(dataframe_t *df, FILE *file) |
| 39 | +{ |
| 40 | + fprintf(file, "[\n"); |
| 41 | + for (int row = 0; row < df->nb_rows; row++) { |
| 42 | + fprintf(file, " {\n"); |
| 43 | + for (int col = 0; col < df->nb_columns; col++) { |
| 44 | + write_value(df->data[row][col], file, df->column_type[col], |
| 45 | + df->column_names[col]); |
| 46 | + fprintf(file, "%s", col < df->nb_columns - 1 ? ",\n" : "\n"); |
| 47 | + } |
| 48 | + fprintf(file, " }%s", row < df->nb_rows - 1 ? ",\n" : "\n"); |
| 49 | + } |
| 50 | + fprintf(file, "]\n"); |
| 51 | +} |
| 52 | + |
| 53 | +int df_write_json(dataframe_t *df, char const *path) |
| 54 | +{ |
| 55 | + int fd; |
| 56 | + FILE *file; |
| 57 | + |
| 58 | + if (df == NULL || !df->nb_rows || !df->nb_columns) |
| 59 | + return -1; |
| 60 | + fd = open(path, O_CREAT | O_WRONLY, 0644); |
| 61 | + if (!fd) |
| 62 | + return -1; |
| 63 | + file = fdopen(fd, "w"); |
| 64 | + if (file == NULL) |
| 65 | + return (close(fd), -1); |
| 66 | + write_values(df, file); |
| 67 | + fclose(file); |
| 68 | + close(fd); |
| 69 | + return 0; |
| 70 | +} |
0 commit comments