cat, wc and grep

Reading time ~1 minute

cat Programm in C - Musterlösung

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

#define SIZE 1024

int main(int argc, char const *argv[])
{
    FILE* file;
    char buffer[SIZE];

    if (argc < 2)
        file = stdin;
    else
    {
        file = fopen(argv[1], "r");
        if (file == NULL)
        {
            fprintf(stderr, "Error opening %s.\n", argv[1]);
            return EXIT_FAILURE;
        }
    }

    while (fgets(buffer, SIZE, file) != NULL)
        fprintf(stdout,"%s",buffer);

    fclose(file);
    return EXIT_SUCCESS;
}

wc Programm in C - Musterlösung

#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>


int main(int argc, char const *argv[])
{
    FILE* file;
    int current_char;

    uint64_t bytes = 0;
    uint64_t words = 0;
    uint64_t lines = 0;

    if (argc < 2)
        file = stdin;
    else
    {
        file = fopen(argv[1], "r");
        if (file == NULL)
        {
            fprintf(stderr, "Error opening %s.\n", argv[1]);
            return EXIT_FAILURE;
        }
    }

    while ((current_char = fgetc(file)) != EOF)
    {
        bytes++;
        if (current_char == '\n')
            lines++;

        switch (current_char)
        {
            case ' ' : words++; break;
            case '\t': words++; break;
            case '\n': words++; break;
            case '\r': words++; break;
            default  : break;
        }
    }

    fprintf(stdout,"words: %"PRIu64" \tlines: %"PRIu64" \t bytes: %"PRIu64"\n"\
            , words, lines, bytes);

    fclose(file);
    return EXIT_SUCCESS;
}

grep Programm in C - Musterlösung

.:TODO?:.