Home > Enterprise >  Why fread() giving extra garbage value
Why fread() giving extra garbage value

Time:11-07

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?

CodePudding user response:

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';

CodePudding user response:

The file content does not end with the null char. Your should reset the allocated memory buffer with 0, since it's unknown how many bytes will be read.

content = (char *)malloc(length   1);
memset(content, 0, length   1);
fread(content, 1, length, file);

Or you should set the data length while printing

length = fread(content, 1, length, file);
printf("%.*s\n", length, content);

See Is there a way to specify how many characters of a string to print out using printf()?

  • Related