c-md/srcs/map/io.c.md
2026-01-12 16:22:13 +01:00

117 lines
2.1 KiB
Markdown

# io.c
Input/output functions for c-md mapping files.
---
## Includes
```c
#include <stdio.h>
#include "map.h"
#include "internal/map_internal.h"
```
---
## Forward Declarations
```c
static int8_t write_header(FILE *f, const char *source, const char *target);
static int8_t write_ranges(FILE *f, t_map *map);
```
---
## Function Descriptions
### `map_write`
Writes a c-md mapping file to the specified path.
#### Parameters
- `map`: Pointer to the mapping structure.
- `path`: Pointer to the output file path string.
- `source`: Pointer to the source file name string.
- `target`: Pointer to the target file name string.
#### Return Value
Return 0 on success, or 1 on failure.
##### Implementation
```c
int8_t
map_write(t_map *map, const char *path, const char *source, const char *target)
{
FILE *f;
int8_t ret;
f = fopen(path, "w");
if (NULL == f)
{
perror(path);
return (1);
}
ret = write_header(f, source, target);
if (0 == ret)
ret = write_ranges(f, map);
fclose(f);
return (ret);
}
```
### `write_header`
Writes the header of a c-md mapping file. (v1 format)
#### Parameters
- `f`: Pointer to the output file.
- `source`: Pointer to the source file name string.
- `target`: Pointer to the target file name string.
#### Return Value
Return 0 on success, or 1 on failure.
#### Implementation
```c
int8_t
write_header(FILE *f, const char *source, const char *target)
{
if (0 > fprintf(f, "C-MD MAP v1\n"))
return (1);
if (0 > fprintf(f, "source: %s\n", source))
return (1);
if (0 > fprintf(f, "target: %s\n", target))
return (1);
if (0 > fprintf(f, "---\n"))
return (1);
return (0);
}
```
### `write_ranges`
Writes the ranges of a c-md mapping file.
#### Parameters
- `f`: Pointer to the output file.
- `map`: Pointer to the mapping structure.
#### Return Value
Return 0 on success, or 1 on failure.
#### Implementation
```c
int8_t
write_ranges(FILE *f, t_map *map)
{
size_t i;
t_range *r;
i = 0;
while (i < map->count)
{
r = &map->ranges[i];
if (0 > fprintf(f, "%u-%u:%u-%u\n",
r->src_start, r->src_end, r->dst_start, r->dst_end))
return (1);
i++;
}
return (0);
}
```