在c++中写入和读取二进制文件

Writing and reading in and from a binary file in c++

本文关键字:读取 二进制文件 c++      更新时间:2023-10-16

我是一个处理文件的初学者。我想在代码中做的是从用户那里获得一个名称,并将其隐藏在.bmp图片中。并且能够再次从文件中获得名称。但我想先把字符转换成ASCII码(这是我的作业要求)

我想做的是把名字的字符改为ASCII码,然后把它们添加到bmp图片的末尾,我将以二进制模式打开。在添加它们之后,我想从文件中读取它们,并能够再次获得名称。

这是我到目前为止所做的。但我没有得到一个正确的结果。我得到的只是一些无意义的字符。这段代码正确吗?

int main()
{
    cout<<"Enter your name"<< endl; 
    char * Text= new char [20];
    cin>> Text;    // getting the name

    int size=0;
    int i=0;     
    while( Text[i] !='')          
    {
        size++;
        i++;
    }

int * BText= new int [size];
for(int i=0; i<size; i++)
{
    BText[i]= (int) Text[i];  // having the ASCII codes of the characters.
}

    fstream MyFile;
MyFile.open("Picture.bmp, ios::in | ios::binary |ios::app");  

    MyFile.seekg (0, ios::end);
ifstream::pos_type End = MyFile.tellg();    //End shows the end of the file before adding anything

    // adding each of the ASCII codes to the end of the file.
    int j=0;
while(j<size)
{
    MyFile.write(reinterpret_cast <const char *>(&BText[j]), sizeof BText[j]);
    j++;
}

MyFile.close();

char * Text2= new char[size*8];
MyFile.open("Picture.bmp, ios:: in , ios:: binary");

    // putting the pointer to the place where the main file ended and start reading from there.
    MyFile.seekg(End);
    MyFile.read(Text2,size*8);

cout<<Text2<<endl;

MyFile.close();
system("pause");
return 0;

}

你的代码中有许多缺陷,其中一个重要的是:

MyFile.open("Picture.bmp, ios::in | ios::binary |ios::app");
必须

MyFile.open("Picture.bmp", ios::in | ios::binary |ios::app);
            ^           ^
            |           |
            +-----------+

,

第二,使用std::string代替c风格的字符串:
char * Text= new char [20];
应该

std::string Text;

,

同样,使用std::vector创建一个数组:

int * BText= new int [size];
应该

std::vector<int> BText(size);

等等

写入int(32位)但读取char(8位)

为什么不按原样写字符串?不需要将其转换为整数数组。

而且,你不会终止你读进的数组

您的写入操作不正确,您应该直接传递完整的文本MyFile.write(reinterpret_cast <const char *>(BText), sizeof (*BText));

同样,将字符串转换为int型并返回为字符将在字符之间插入空格,这在读取操作中是没有考虑到的