PDA

Click to See Complete Forum and Search --> : fread and char *


slashandburn
Aug 15th, 2002, 04:29 PM
Im trying to read in a file to a char * with fread, but after it is done there is junk at the end, how can i fix this.

Here is an excert from my class


void mikestring::readfile(char * filename)
{

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

fseek (f , 0 , SEEK_END);
long fileSize = ftell (f);
rewind (f);

delete[] mystring; //Clear Old Memmory

MyLen = fileSize;
MyCap = MyLen+1;

mystring = new char[fileSize];
fread (mystring,1,fileSize,f);

fclose(f);

}

jim mcnamara
Aug 17th, 2002, 08:59 AM
Your code looks okay. Since you are doing a binary read -
IF the file was originally written as a text file, there will be an ascii 26 character that marks the end of the text file. fread ignores this EOF mark and reads beyond it - the junk you see.

Try getting rid of junk like this:

char *start=mystring;
char *buf= strchr(mystring,26);
if(buf!=NULL)
while( ((int)buf - (int)start ) >=filesize) *buf++=0x00;


Don't do this to a binary-created file, you will clobber good data.