简体   繁体   中英

C++: Reading Binary Files

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. ie read all characters till 0x00, skip 50 bytes and continue till end of file.What is the best way to do it 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM