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.
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!