开发者

C++: Reading Binary Files

开发者 https://www.devze.com 2023-03-15 08:45 出处:网络
I have a Binary file that has several names followed by some details (50 bytes fixed). Each name is followed by 0X00 followed by the 50 byte details. I need to extract just the names from the file. i.

I have a Binary file that has several names followed by some details (50 bytes fixed). Each name is followed by 0X00 followed by the 50 byte details. I need to extract just the names from the file. i.e read all characters till 0x00, skip 50 bytes and continue till end of file.What is the best way to do i开发者_如何学编程t in 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();
...


In the 'learn a man to fish' department: www.cplusplus.com

Simplistic approach:

#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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号