Jump to: navigation, search

This code was used for the review of puts :

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

void fail(const char *format, ...)
{
    va_list arguments;
    va_start(arguments, format);
    fprintf(stderr, "Error: ");
    vfprintf(stderr, format, arguments);
    fputc('\n', stderr);
    perror("perror output");
    exit(EXIT_FAILURE);
}

typedef void (*run_function_func_ptr_type)();

char *read_file_as_string(FILE * fp)
{
    if (fseek(fp, 0, SEEK_END) != 0)
	fail("fseek failed");

    long file_size = ftell(fp);
    if (file_size == -1)
	fail("ftell failed");

    rewind(fp);

    char *result = malloc(file_size + 1);
    if (result == NULL)
	fail("malloc failed");

    size_t fread_result = fread(result, 1, file_size, fp);
    if (fread_result != file_size)
	fail("fread returned %zu instead of %zu", fread_result, file_size);

    result[file_size] = '\0';
    return result;
}

char *run_function_and_get_stdout(run_function_func_ptr_type function)
{
    FILE *fp = freopen("output", "w+", stdout);
    if (fp == NULL)
	fail("freopen of stdout to output failed");

    function();
    char *output = read_file_as_string(fp);

    if (fclose(fp) != 0)
	fail("fclose failed");

    if (remove("output") != 0)
	fail("failed to delete temporary output file");

    return output;
}

int clc_puts(const char *s)
{
    while (*s) {
	if (putchar(*s++) == EOF)
	    return EOF;
    }

    if (putchar('\n') == EOF)
	return EOF;

    return 0;
}

static const char *printed_string;
static const char *printed_string_with_newline;

void test_puts()
{
    int result = clc_puts(printed_string);
    if (result < 0)
	fail("puts returned %d instead of a non-negative number", result);
}

void do_test_output()
{
    char *output = run_function_and_get_stdout(test_puts);
    if (strcmp(output, printed_string_with_newline))
	fail("puts printed \"%s\" instead of \"%s\"", output,
	     printed_string_with_newline);

    free(output);
}

int main()
{
    printed_string = "test string";
    printed_string_with_newline = "test string\n";
    do_test_output();

    printed_string = "string";
    printed_string_with_newline = "string\n";
    do_test_output();

    printed_string = "12847912895r1u2q1t";
    printed_string_with_newline = "12847912895r1u2q1t\n";
    do_test_output();

    printed_string = "";
    printed_string_with_newline = "\n";
    do_test_output();

    printed_string = "^ß0ß491";
    printed_string_with_newline = "^ß0ß491\n";
    do_test_output();

    return 0;
}
Personal tools