When fread is used twice, the second time it seems to overwrite the first time's output. Is there any way to clear fread's internal buffer after each use ?
char *FILEREAD(const char *FILENAME)
{
static char READBUFFER[15001] = "";
READBUFFER[0] = '\0'; // try to solve the problem but this will not
FILE *FILE1 = fopen(FILENAME, "r");
fread(READBUFFER, 1, 15000, FILE1);
fclose(FILE1);
return READBUFFER;
}
int main(void)
{
printf("%s\n", FILEREAD("file1.txt")); // file content is: "wwwww" and FILEREAD outputs "wwwww"
printf("%s\n", FILEREAD("file2.txt")); // file content is: "aaa" and FILEREAD outputs "aaaww"
return 0;
}
The problem isn't fread, but what you expect of it. According to the man page fread(3) it reads a certain amount of bytes from a file pointer, and copies them to a character array. It say nowhere that the target is cleared up front, or that it'll put a '\0' at the end, it leaves that to the programmer.
What you need, is to set the byte past the amount of characters read by fread to '\0', or in your example READBUFFER[3]='\0'. Fortunately, fread() returns the number of items read, so: