簡體   English   中英

C ++:讀取二進制文件

[英]C++: Reading Binary Files

我有一個二進制文件,該文件具有多個名稱,后跟一些詳細信息(固定50個字節)。 每個名稱后跟0X00,后跟50個字節的詳細信息。 我只需要從文件中提取名稱。 例如,讀取所有字符直到0x00,跳過50個字節並繼續到文件末尾。用C ++做到這一點的最佳方法是什么。

#include <fstream>
#include <string>

...
std::ifstream file("filename");
if ( ! file.is_open() )
  return;

std::string name;
char data[50];

while ( std::getline( file, name, '\0' ) && file.read( data, 50 ) )
{
  // you could use name and data
}
file.close();
...

在“學釣魚的人”部門: www.cplusplus.com

簡化方法:

#include <fstream>
#include <iostream>   

int main()
{
    char buf[50];
    std::ifstream ifs("data.bin", std::ios_base::binary | std::ios_base::in);
    while (ifs.read(buf, sizeof(buf)))
    {
        if (!ifs.eof())
        {
            std::cout << std::string(buf) << std::endl;
        }
    }

    std::cout << "Done" << std::endl;
    ifs.close();

    return 0;
}

暫無
暫無

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

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