Reading from a file.
Hi, it's been a while since I've asked a question here. Hopefully someone could help me out.
I'm simply trying to read a file using fread and output the contents. It's partially working. It outputs everything correctly but it ends with a bunch of random characters.
Code:
#include <iostream>
using namespace std;
void ReadFile(char* filename,char*& buffer)
{
FILE *file = fopen(filename,"rb");
fseek(file,0,SEEK_END);
int size = ftell(file);
rewind(file);
buffer = new char[size];
memset(buffer,0,size);
int r = fread(buffer,1,size,file);
cout << buffer;
fclose(file);
}
int main()
{
char* buffer;
ReadFile("test.txt",buffer);
cin.get();
}
Let's say 'size' is 50 in this instance. for some reason, the size of buffer ends up 55 or 56 after fread is called. I emptied the buffer before using it and tried outputting it, everything is normal (it's empty). Right after the call to fread the buffer somehow gets bigger and is filled with random characters. I've opened the text file in a hex editor to ensure there isn't anything I'm not seeing but there isn't. The file is 50 bytes. fread returns the amount of bytes read, in this case returned to 'r', 'r' is what it should be. so where the motherfuck are these bytes coming from?
I can't for the life of me figure out how this is happening. Help pls.
ive been using fread for such a long time and this has never happened to me. this is driving me insane.
---------- Post added at 02:21 PM ---------- Previous post was at 12:40 PM ----------
Nevermind I'm retarded. Someone close this pls.