Results 1 to 2 of 2

Thread: fread and char *

  1. #1

    Thread Starter
    Addicted Member slashandburn's Avatar
    Join Date
    Aug 1999
    Location
    Marietta, Ga
    Posts
    229

    fread and char *

    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

    Code:
    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);
    
    }

  2. #2
    Frenzied Member
    Join Date
    Jul 2002
    Posts
    1,370
    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:
    Code:
      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.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width