用ifstream读取.exe文件的二进制文件 [英] reading .exe file with ifstream by binary

查看:469
本文介绍了用ifstream读取.exe文件的二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所说,我试图以二进制方式使用ifstream读取.exe文件。但它总是会遗漏一些字节,因此新复制的.exe文件不合法。我试着评论f_write语句,问题仍然存在。



代码如下所示。

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.

推荐答案

当您读入字节时,iostream对象可能会跳过换行符(ascii 10或0x0a)。在复制之前尝试插入以下行:

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);





编辑:逐字节复制文件无效。读取整个文件然后将其写入一个大块也是一个坏主意,因为在这种情况下你将无法复制大文件。最好的是黄金中间方式,使用缓冲区(很少,可能是4-16千字节)作为读取/写入数据有效的单位。



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.


@pasztoripisti非常感谢。它有效。
@pasztoripisti thanks very much. it works.


这篇关于用ifstream读取.exe文件的二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆