Search code examples
cfgets

c: fgets function reads file but does not print out into terminal


I have the following program copied from a tutorial about C's fgets(). It won't print out the contents of the file into the terminal:

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

#define MAX_TEXT 1000

int main(int argc, char *argv[])
{
    FILE *file = NULL;
    char str[MAX_TEXT] = "";

    file = fopen("test.txt", "r");

    if(file != NULL) {
        fgets(str, MAX_TEXT, file);
        printf("%s", str);
        fclose(file);
    }
    else {
        printf("cannot read the file\n");
    }

    return 0;
}

The only result I get is the letter t. The t is preceded by a small transparent square.

For your information I am using code::blocks ide on Windows. All the previous code snippets (fputc(), fputs()...) worked fine.


Solution

  • Your program makes no effort to figure out what's in the file and present it in a sensible way. So it's not surprising that it makes a mess out of rich text. Modern "text" files are frequently not just raw ASCII characters but contain support for wide characters, endianness markers, and all kinds of other things.