# read stdin en C

description : Éxemple de lecture du flux stdin en C
categories : Coding;
tags : C;

Éxemple de lecture du flux stdin en C

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <stdio.h>
#include <stdint.h>
#include <err.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    const size_t CHUNK_SIZE = 64;
    size_t size = CHUNK_SIZE, read = 0, ret = 0;
    uint8_t *bytes = NULL;

    if ((freopen(NULL, "rb", stdin)) == NULL)
        errx(EXIT_FAILURE, "freopen(stdin) : %s", strerror(errno));

    if ((bytes = malloc(sizeof(uint8_t) * size)) == NULL)
        errx(EXIT_FAILURE, "malloc(sizeof(uint8_t) * %lu) : %s", size, strerror(errno));

    while ((ret = fread(&bytes[read], sizeof(uint8_t), CHUNK_SIZE, stdin)) != 0)
    {
        read += ret;

        size += CHUNK_SIZE;

        bytes = realloc(bytes, sizeof(uint8_t) * size);

        if (bytes == NULL)
            errx(EXIT_FAILURE, "realloc(sizeof(uint8_t) * %lu) : %s", size, strerror(errno));
    }

    if (ferror(stdin) != 0) errx(EXIT_FAILURE, "ferror(stdin) : %s", strerror(errno));

    printf("nbr bytes read : %lu\n", read);

    for (int i = 0; i < read; i++) printf("0x%.2x ", bytes[i]);

    free(bytes);

    return 0;
}
1
echo -ne "\x01\x10" | ./c-read-stdin-binary 
1
2
nbr bytes read : 2
0x01 0x10