Why does my FileRead append extra garbage to data?

Hello.

I made simple function which should return file contents but for some reason I get extra garbage data appended to file contents.

1
2
3
4
5
6
7
8
9
10
char* FileRead(char* FileName){
	FILE* f = fopen(FileName,"r");
	fseek (f , 0 , SEEK_END);
	long  lSize = ftell (f);
	rewind (f);
	char * buffer = (char*) malloc (sizeof(char)*lSize);
	fread(buffer,1,lSize ,f);
	fclose(f);
	return buffer;
}


Here's how I call it: printf(FileRead("C:\\main.cpp"));

It appends this to string: ═══════════════════════════════²²²²½½½½½½½½Ņ■Ņ■
Last edited on
You need to open the file in binary mode in order for the data to match the length of the buffer. In text mode, the end of line markers may be automatically translated during input or output.

FILE* f = fopen(FileName,"rb");

Also, you do not pass back to the calling function any way to determine the length of the data. If you want the buffer to be null-terminated like an ordinary c-string, you need to allocate an extra byte (increase the size of the buffer by 1) and manually add the terminating zero after reading the data.

Otherwise there is a risk that whatever random data resides in the memory locations following your buffer will be interpreted as part of the data, until by accident a zero byte is encountered.
Last edited on
\0 helped..

But why doesnt it auto stop when it reaches at buffer size?
why doesnt it auto stop

What is "it"?

If you are asking about printf(), then it recognises the end of a string when the null character is found.

Note, the fread() function does stop when it reaches the end of the data.

The return value from fread() is the number of bytes which were read. In binary mode, this should be the same as the number of bytes requested (except in the case of some error). In text mode, the returned value may be less than the number requested (depending on the file contents and OS).
http://www.cplusplus.com/reference/cstdio/fread/
Last edited on
Topic archived. No new replies allowed.