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

1.4 KiB

streams.c

Funtions for handling input and output streams.


Includes

#include <stdio.h>

#include "io.h"

Function Descriptions

io_open

Opens input and output streams based on provided file paths. if input_path is NULL, stdin is used. if output_path is NULL, stdout is used.

Parameters

  • io: Pointer to the t_io structure to hold the opened streams.
  • input_path: Path to the input file, or NULL for stdin.
  • output_path: Path to the output file, or NULL for stdout.

Return Value

Returns 0 on success, or 1 on failure. The caller is responsible for closing the streams using io_close.

Implementation

int8_t
io_open(t_io *io, const char *input_path, const char *output_path)
{
	io->in = (NULL != input_path) ? fopen(input_path, "r") : stdin;
	if (NULL == io->in)
	{
		perror(input_path);
		return (1);
	}
	io->out = (NULL != output_path) ? fopen(output_path, "w") : stdout;
	if (NULL == io->out)
	{
		perror(output_path);
		if (io->in != stdin)
			fclose(io->in);
		return (1);
	}
	return (0);
}

io_close

Closes the input and output streams if they are not stdin or stdout.

Parameters

  • io: Pointer to the t_io structure containing the streams to close.

Implementation

void
io_close(t_io *io)
{
	if (NULL != io->in && io->in != stdin)
		fclose(io->in);
	if (NULL != io->out && io->out != stdout)
		fclose(io->out);
}