Search code examples
cpointersmallocfread

Why fread() giving extra garbage value


I am reading content of a file and and trying to print it, but it is giving extra garbage value.

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

int main() {
    long length;
    char* content;
    FILE *file = fopen("text.txt", "r");
    fseek(file, 0, SEEK_END);
    length = ftell(file);
    fseek(file, 0, SEEK_SET);
    content = (char *)malloc(length);
    fread(content, 1, length, file);
    printf("%s\n", content);
    return 0;
}

image

Maybe I have to null terminate content[length] = '\0';?

The more \n newline characters the file has at the end, the more garbage I get.

Any solution, except using calloc?


Solution

  • If that is MSVC (clued by #define _CRT_SECURE_NO_DEPRECATE) then the file mode is probably text by default, and all the CR-LF pairs will be shrunk to a single LF when you read it. Getting the file size does not take that into account. Use the number of characters actually read to terminate the string.

    content = malloc(length + 1);           // room for terminator
    size_t bytes = fread(content, 1, length, file);
    content[bytes] = '\0';