/*
 * ler - Exibe o conteúdo de arquivos (análogo ao cat)
 * Uso: ler [arquivo...]
 * Se nenhum arquivo for informado, lê da entrada padrão (stdin).
 */

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

#define BUFFER_SIZE 4096

static void exibir_arquivo(FILE *fp, const char *nome) {
    char buf[BUFFER_SIZE];
    size_t n;

    while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) {
        if (fwrite(buf, 1, n, stdout) != n) {
            fprintf(stderr, "ler: erro ao escrever na saída padrão\n");
            exit(EXIT_FAILURE);
        }
    }
    if (ferror(fp)) {
        fprintf(stderr, "ler: erro ao ler '%s': %s\n", nome, strerror(errno));
        exit(EXIT_FAILURE);
    }
}

int main(int argc, char *argv[]) {
    if (argc < 2) {
        /* Sem argumentos: lê do stdin */
        exibir_arquivo(stdin, "stdin");
        return EXIT_SUCCESS;
    }

    for (int i = 1; i < argc; i++) {
        const char *nome = argv[i];

        if (strcmp(nome, "-") == 0) {
            exibir_arquivo(stdin, "stdin");
            continue;
        }

        FILE *fp = fopen(nome, "r");
        if (!fp) {
            fprintf(stderr, "ler: erro ao abrir '%s': %s\n", nome, strerror(errno));
            continue;
        }

        exibir_arquivo(fp, nome);
        fclose(fp);
    }

    return EXIT_SUCCESS;
}
