Originally Posted by
Coool Steve
Hey there.
I've been having this issue for awhile, and its not too bad. Its just, whenever I use fread to read from a text file to print to the screen, it also prints random characters that aren't suppose to be there. I've tried looking on Google but couldn't find an answer. Well, I did find answers but none of them worked for me.
Code:
FILE *title;
char titlestr[713];
title = fopen(".//text//title.txt", "r");
fread(titlestr, sizeof(titlestr), 1, title);
printf("%s", titlestr);
Fist off... sizeof(titlestr) is extremely unreliable. You should define a constant and use that instead...
Code:
#define TSTRLEN 713
fread(titlestr, TSTRLEN,1, title);
But this only works if titlestr is *always exactly* 713 characters long... In any other case you will either get only part of the string or you'll end up reading past the end of the string into whatever else is in the file.
That's my current code; why are random characters being printed?
Because the string is not null terminated... Of that 713 characters you need to know how many are actually used... before you can print it.
Here's a trick you can use...
Code:
#define TSTRLEN 713
FILE *title;
char titlestr[TSTRLEN];
title = fopen(".//text//title.txt", "r");
memset(title,0,TSTRLEN);
fread(titlestr,1, TSTRLEN, title);
printf("%s", titlestr);
Although I think you will find fgets() would be a far better way to read that string from disk.