Skip to content

Commit 3080762

Browse files
committed
Add bonus write to json
1 parent a4e52c0 commit 3080762

File tree

3 files changed

+72
-0
lines changed

3 files changed

+72
-0
lines changed

include/dataframe.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,4 +76,5 @@ dataframe_t *df_apply(dataframe_t *df, const char *column,
7676
void *(*apply_func)(void *vl));
7777
dataframe_t *df_to_type(dataframe_t *df, char const *column,
7878
column_type_t downcast);
79+
int df_write_json(dataframe_t *df, char const *path);
7980
#endif /* !DATAFRAME_H_ */

src/df_write_json.c

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
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+
}

tests/main.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ int main(int ac, char **av)
6666
if (df == NULL)
6767
return 84;
6868
df_write_csv(df, "result.csv");
69+
df_write_json(df, "result.json");
6970
printf("nb_columns= %d\n", df->nb_columns);
7071
printf("nb_rows= %d\n", df->nb_rows);
7172
df_info(df);

0 commit comments

Comments
 (0)