开发者

How do I copy the binary code of an executable into a new file without using a system copy command?

This is the code I have, but the file is a little smaller and doesn't execute:

int WriteFileContentsToNewFile(string inFilename, string outFilename)
{
    ifstream infile(inFilename.c_str(), ios::binary);
    ofstream outfile(outFilename.c_str(), ios::binary);

    string line;
    // Initial read
    infile >> line;
    outfile << line;
    // Read the rest
    while( infile )
    { 
        infile >> line;
        outfile << line;
    }

    infile.close();
    outfile.close();

    return 0;
}

What am I doing wrong? Is there a better way to read in the binary of an executable file and immediately write it out to another name? Any code examples?

I need to do it without a sy开发者_如何学运维stem copy in order to simulate writing to disk.


One way is to use the stream inserter for a streambuf:

int WriteFileContentsToNewFile(string inFilename, string outFilename)
{
    ifstream infile(inFilename.c_str(), ios::binary);
    ofstream outfile(outFilename.c_str(), ios::binary);

    outfile << infile.rdbuf();
}


The stream operator>>() performs formatted input even if you open the stream in binary mode. Formatted input expects to see strings of printable characters separated by spaces, but this is not what binary files like executables consist of. You need to read the file with the stream's read() function, and write it with the output stream's write() function.


Off the top of my head: (no error checking)

EDIT: Changed to fix feof bug.

int WriteFileContentsToNewFile(string inFilename, string outFilename)
{
  FILE* in = fopen(inFilename.c_str(),"rb");
  FILE* out = fopen(outFilename.c_str(),"wb");
  char buf[4096]; //1024 is a habit of mine. 4096 is most likely your blocksize. it could also be 2<<13 instead.
  int len;
  while( (len = fread(buf,1,1024,in)) > 0 )
  {
    fwrite(buf,1,len,out);
  }
  fclose(in);
  fclose(out);
}


(unix) the system cp command not only copies the contents of the file, but also copies (some) of the file permissions, which include the execute bit.

Make sure your copy also sets the execute bit on the output file as appropriate.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜