+ -
当前位置:首页 → 问答吧 → c++ 二进制文件读写

c++ 二进制文件读写

时间:2011-12-08

来源:互联网

我今天写了一个小程序,把sub.dll文件中的内容复制到sub2.lib文件中,因为dll和lib文件都是二进制文件,所以是二进制文件的读写操作,可奇怪的是复制到sub2.lib中的内容第一个字节是错的,而其余的全是对的。我很纳闷,请高手指教。程序如下:
#include<fstream>
#include<iostream>
using namespace std;


int main()
{
ifstream fin("sub.dll",ios::in|ios::binary);
ofstream fout("sub2.lib",ios::out|ios::binary);

if(!fout)
{
cout<<"Cannot open output file";
exit(1);
}
if(!fin)
{
cout<<"Cannot open the input file!"<<endl;
exit(1);
}

char *ch = (char *)malloc(sizeof(char));

while(!fin.eof())
{
fout.write(ch,sizeof(char));
fin.read(ch,sizeof(char));
}
fin.close();
fout.close();
return 0;
}

sub.dll中的内容:

MZ  @ ? ???L?This program cannot be run in DOS mode.

$ .q!頹O絡O絡O絓6D絢O介A絶O絓6E絊O絡N?O?\絠O絺D絢O絺K絢O絉ichjO PE L ?轓 ! @ ` ? P 怹 > V ( P .text j? @ `.rdata ? P P @ @.data 1 ` 0 ` @ ?reloc ? @ B  


而sub2.lib中的内容是:
蚆Z  @ ? ???L?This program cannot be run in DOS mode.

$ .q!頹O絡O絡O絓6D絢O介A絶O絓6E絊O絡N?O?\絠O絺D絢O絺K絢O絉ichjO PE L ?轓 ! @ ` ? P 怹 > V ( P .text j? @ `.rdata ? P P @ @.data 1 ` 0 ` @ ?reloc ? @ B

作者: coko_fly   发布时间: 2011-12-08

应该先读一个字节,后写一个字节
fin.read(&ch,1);
fout.write(&ch,1);
lz的顺序颠倒了:
fout.write(ch,sizeof(char));
fin.read(ch,sizeof(char));

C/C++ code

#include<fstream>
#include<iostream>
using namespace std;

int main()
{
    ifstream fin("sub.dll",ios::in|ios::binary);
    ofstream fout("sub2.lib",ios::out|ios::binary);
    
    if(!fout)
    {
        cout<<"Cannot open output file";
        exit(1);
    }
    if(!fin)
    {
        cout<<"Cannot open the input file!"<<endl;
        exit(1);
    }
    
    char ch;
    
    while(!fin.eof())
    {
        fin.read(&ch,1);
        fout.write(&ch,1);
    }
    fin.close();
    fout.close();
    return 0;
}

作者: wangliangffaflgh   发布时间: 2011-12-08