C reading from file

Here’s an example of how i would implement PrintFile, hope it helps.

#include <stdio.h>

int PrintFile(const char *filename);

int PrintFile(const char *filename)
{
    FILE *file = fopen(filename, "r");

    if (file == NULL)
    {
        return -1;
    }

    int c = 0;
    int i = 0;

    while ((c = fgetc(file)) != EOF)
    {
        if (isprint(c))
        {
            fputc(c, stdout);
            i++;
        }
        else
        {
            fputc('?', stdout);
        }
    }

    if (ferror(file))
    {
        return -2;
    }

    return i;
}

Browse More Popular Posts

Leave a Comment