erase fread 's internal buffer ?

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.

2 ways to solve this:

  1. memset(3) the array first
  2. fread returns the number of characters read. Put a '\0' behind that.

When you call FILEREAD the first time, we have

READBUFFER[0]='w'
READBUFFER[1]='w'
READBUFFER[2]='w'
READBUFFER[3]='w'
READBUFFER[4]='w'
READBUFFER[5]='\0'

The second time, you set READBUFFER[0]='\0', but then the fread fills the first 3 elements with "aaa", so now

READBUFFER[0]='a'
READBUFFER[1]='a'
READBUFFER[2]='a'
READBUFFER[3]='w'
READBUFFER[4]='w'
READBUFFER[5]='\0'

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:

size_t n;
...
n = fread(...)
READBUFFER[n]='\0'; 

should do the trick.

Cheers,
Lo�c.