Click here to Skip to main content
12,629,107 members (34,703 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: C++
as the title said, I tried to read a .exe file using ifstream in binary way. but it always miss some bytes, so the newly copied .exe file is not legal. I tried to comment the f_write statement, the problem still there.

code looks like following.
int main(int argc, char *argv[])
{
        if (argc != 3)
        {
                cerr << "Error! \n filecopy.exe srcfilename destfilename" << endl;
                return 0;
        }
        
        ifstream f_read (argv[1],ios::binary | ios::in);
    	ofstream f_write(argv[2],ios::binary | ios::out);
 
        char i;
 
        if (f_read == NULL)
        {
          return 0;
        }
                
        while (f_read >> i)
        {
           f_write << i;
        }
 
        f_read.close();
        f_write.close();
 
        return 0; 
}

Any tips will be appreciate.
Posted 20-Jul-13 9:20am
Comments
   
Okay, you can read EXE file, but what are you going to do with it? If you want to parse it, this is a well-known problem, you can find enough code samples...
—SA
BianChengNan 21-Jul-13 23:28pm
   
thanks for your reply. just want to find out the reason. no really job to do.
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

Probably the newline characters (ascii 10 or 0x0a) are skipped by the iostream object when you are reading in the bytes. Try inserting the following line before doing the copy:
f_read.unsetf(ios::skipws);

EDIT: copying a file byte-by-byte is not effective. Reading in the whole file and then writing it out in one big piece is also a bad idea as in that case you wouldn't be able to copy huge files. The best is the golden middle way, using a buffer (few, maybe 4-16 kilobytes) as a unit for reading/writing data to be effective.
  Permalink  
v2
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

@pasztoripisti thanks very much. it works.
  Permalink  
Comments
pasztorpisti 22-Jul-13 3:15am
   
You are welcome! Next time use the "Have a Question or Comment" button below the answer you want to comment on instead of adding the comment as an answer, that way the answer owner receives notification about your message.
BianChengNan 29-Jul-13 2:10am
   
OK, I got it.thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web02 | 2.8.161205.3 | Last Updated 21 Jul 2013
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100