Click here to Skip to main content
15,896,207 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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.
C++
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
Comments
Sergey Alexandrovich Kryukov 21-Jul-13 1:10am    
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
BCN-163 21-Jul-13 23:28pm    
thanks for your reply. just want to find out the reason. no really job to do.

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:
C++
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.
 
Share this answer
 
v2
@pasztoripisti thanks very much. it works.
 
Share this answer
 
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.
BCN-163 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)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900