82 lines
2.2 KiB
C
82 lines
2.2 KiB
C
#include "cli.h"
|
|
#include <errno.h>
|
|
#include <string.h>
|
|
|
|
static void report_open(const char *kind, const char *path)
|
|
{
|
|
fprintf(stderr, "%s %s: %s\n", kind, path, strerror(errno));
|
|
}
|
|
|
|
int replay_cli_close(ReplayCli *cli)
|
|
{
|
|
int failed = 0;
|
|
if (cli->own_input) {
|
|
if (fclose(cli->input) != 0) {
|
|
failed = 1;
|
|
}
|
|
cli->own_input = 0;
|
|
}
|
|
if (cli->own_output) {
|
|
if (fclose(cli->output) != 0) {
|
|
failed = 1;
|
|
}
|
|
cli->own_output = 0;
|
|
} else if (fflush(cli->output) != 0) {
|
|
failed = 1;
|
|
}
|
|
return failed ? 3 : 0;
|
|
}
|
|
|
|
int replay_cli_open(ReplayCli *cli, int argc, char **argv)
|
|
{
|
|
int index;
|
|
const char *input_path = NULL;
|
|
const char *output_path = NULL;
|
|
memset(cli, 0, sizeof(*cli));
|
|
cli->input = stdin;
|
|
cli->output = stdout;
|
|
for (index = 1; index < argc; index++) {
|
|
if (strcmp(argv[index], "--help") == 0 && argc == 2) {
|
|
cli->help = 1;
|
|
puts("usage: replay [--input FILE] [--output FILE]");
|
|
return 1;
|
|
}
|
|
if (index + 1 >= argc) {
|
|
fprintf(stderr, "missing path argument\n");
|
|
return 0;
|
|
}
|
|
if (strcmp(argv[index], "--input") == 0 && input_path == NULL) {
|
|
input_path = argv[++index];
|
|
} else if (strcmp(argv[index], "--output") == 0 && output_path == NULL) {
|
|
output_path = argv[++index];
|
|
} else {
|
|
fprintf(stderr, "unknown or repeated option: %s\n", argv[index]);
|
|
return 0;
|
|
}
|
|
}
|
|
if (input_path != NULL && output_path != NULL &&
|
|
strcmp(input_path, output_path) == 0) {
|
|
fprintf(stderr, "input and output must be different files\n");
|
|
return 0;
|
|
}
|
|
if (input_path != NULL) {
|
|
cli->input = fopen(input_path, "r");
|
|
if (cli->input == NULL) {
|
|
report_open("input", input_path);
|
|
return 0;
|
|
}
|
|
cli->own_input = 1;
|
|
}
|
|
if (output_path != NULL) {
|
|
cli->output = fopen(output_path, "w");
|
|
if (cli->output == NULL) {
|
|
report_open("output", output_path);
|
|
cli->output = stdout;
|
|
replay_cli_close(cli);
|
|
return 0;
|
|
}
|
|
cli->own_output = 1;
|
|
}
|
|
return 1;
|
|
}
|