簡體   English   中英

如何使用c ++逐字節寫入文件

[英]How to write a file byte by byte using c++

如何使用c ++逐字節寫入文件?

unsigned short array[2]={ox20ac,0x20bc};

如果我有一個十六進制值0x20ac我怎么能用c ++在一個文件中逐字節寫它

你可以嘗試這樣的事情:

#include <fstream>
...

ofstream fout;
fout.open("file.bin", ios::binary | ios::out);

int a[4] = {100023, 23, 42, 13};
fout.write((char*) &a, sizeof(a));

fout.close();

一種選擇,使用標准C ++庫:

#include <fstream>
#include <assert.h>

void main()
{
    unsigned short array[2]={ox20ac,0x20bc};

    std::ofstream file;
    file.open("C:/1.dat", std::ios_base::binary);
    assert(file.is_open());

    for(int i = 0; i < sizeof(array) / sizeof(array[0]); ++i)
       file.write((char*)(array + i * sizeof(array[0])), sizeof(array[0]));
    file.close();
}

或者,您可以輕松地一次性編寫整個數據(無循環):

file.write((const char*)array, sizeof(array));

要打開輸出文件,請使用ofstream(輸出文件流,ostream的子類)。 如果您不確定輸出是否為人類可讀文本(ASCII),請使用ios_base :: binary模式(作為構造函數中的第二個參數或open()成員函數)。

要寫入單個字節,請使用ostream成員函數“put”。 要一次寫入多個字節,請使用ostream成員函數“write”。

有一些方法可以使數據類型(例如int)長於一個字節並將它們用作字節數組。 這有時被稱為類型懲罰,並在其他答案中進行了描述,但要注意字節序和不同大小的數據類型(int可以是2-8個字節),這在不同的機器和編譯器上可能不同。

要測試輸出,請將其重新打開為輸入文件並打印字節。

ifstream in("myfile.txt", ios_base::binary);
while(!in.eof()) printf("%02X ", in.get()); //print next byte as a zero-padded width-2 capitalized hexadecimal).
in.close();

或者像普通人一樣使用十六進制編輯器。

你可以使用寫函數或ostream。 使用c ++函數是ostream。

暫無
暫無

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

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