簡體   English   中英

無法正確地將大的無符號整數寫入二進制文件-C ++

[英]can't write correctly large unsigned ints to binary file - c++

在我的項目中,我需要向二進制文件中寫入連續的無符號整數,並且每個數字必須精確地占4個字節,這一點很重要。 但是,當我使用十六進制編輯器打開二進制文件時,我看到了這種奇怪的情況:數字被正確地寫入,直到9號。 在編號10之前,他將添加另一個額外的字節並寫入“ 13”(並且已經弄亂了我的文件)。 而且奇怪的事情繼續發生-從數字30開始,每個字符都會被寫成不同的字符。 這是為什么? 如何解決,至少是尺寸問題? 這是我的簡單示例代碼:

int main()
{
    string filename;
    cin >> filename;
    fstream mystream;
    mystream.open(filename, ios::out);
    if (mystream)
        for (unsigned int i = 0; i < 3200; i++)
            mystream.write((char*)&i, sizeof(unsigned int));
    mystream.close();

    return 0;
}

並附有我在文件中看到的圖像: 十六進制編輯器中的文件捕獲

謝謝

數字10是換行符LF,由於以文本模式打開文件,因此將其轉換為CRLF。

以二進制模式打開文件以處理二進制文件。

#include <iostream>
#include <fstream>
#include <string>

using std::string;
using std::cin;
using std::fstream;
using std::ios;

int main()
{
    string filename;
    cin >> filename;
    fstream mystream;
    mystream.open(filename, ios::out | ios::binary); // add OR with ios::binary
    if (mystream)
        for (unsigned int i = 0; i < 3200; i++)
            mystream.write((char*)&i, sizeof(unsigned int));
    mystream.close();
}

暫無
暫無

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

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