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;
}
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
?