Weird chars added when open file

This is not the first time I have this problem and I just don't get it
I have this code
1
2
3
4
5
6
7
8
9
10
11
12
char* content; //Declared as a global variable
...
...
long len;
fp = fopen(file_name, "r");
fseek(fp, 0, SEEK_END);
len = ftell(fp);
fseek(fp, 0, SEEK_SET);
content = (char *)malloc(len);
fread(content, len, 1, fp);
fclose(fp);
MessageBox(NULL, content, "File Content", NULL);


The content of the file is read without problems but there are always some weird characters added at the end of the global var content. If the file contains the text "this is my text", for example, when I open the file and show its content into a MessageBox or EDIT control I see something like "this is my textQzCF•›"
I don't know if this is related to pointers or what? It just drive me crazy.
What happens if you do this after fclose(fp);

content[len]=0;

Just curious.
Just tried this out:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <fstream>
#include <windows.h>

const char *file_name = "Text1.txt";

int main()
{
  char *content = 0;
  std::ifstream fs(file_name);
  fs.seekg(0,std::ios_base::end);
  int file_size = fs.tellg();
  fs.seekg(0,std::ios_base::beg);
  content = new char[file_size];
  fs.read(content,file_size);
  MessageBox(0,content,"File Content",0);
  return 0;
}


Not having any odd characters whatsoever in the messagebox. I think your problem is that you have the arguments in fread wrong. Should probably be:

fread(content,1,len,fp);
Most likely the problem is that the value in 'len' doesn't account for null-termination of the string. You probably need to malloc(len + 1) and then set the last char's value to '\0'.
Thank you for so many options you offer for me. It works when I set content[len] = 0. Why is that? Anyway, I should try the code that Texan40 posted too. Thanks again!
Last edited on
It probably happens because you are not receiving a null-termination in your string from the file you read.

Also, as webJose stated, you should malloc len+1.
Last edited on
Yeah, webJose and Lamblion are right.
Topic archived. No new replies allowed.