簡體   English   中英

在C ++中讀寫二進制文件

[英]Writing and reading in and from a binary file in c++

我是使用文件的初學者。 我想在代碼中執行的操作是從用戶那里獲得一個名稱,並將其隱藏在.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] !='\0')          
    {

        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並轉換為char將在字符之間插入空格,而您在閱讀操作時不會考慮這些空格

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM