简体   繁体   中英

how to reading a binary file one byte at time c++

I was trying to read a binary file one bite at time in c++. rather then loading whole file in to memory.it's read half the binary file and crash.is there better way of doing that or can some one fix this?


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

void main() 
{
    std::string input_file_adress = "res/184672.mp3";

    char onecharacter ;
    
    std::ifstream input_file(input_file_adress, std::ios::in | std::ios::binary | std::ios::ate);
    
    if (input_file.is_open())
    {
        const int input_file_size = input_file.tellg();
        input_file.seekg(0);

        std::cout << "file size - " << input_file_size << std::endl;

        const int back = 1;

        //reading input file

        for (size_t i = 0; i < input_file_size; i++)
        {
            onecharacter = 0;

            if (i != 0)input_file.seekg(std::streampos(i - back));
            input_file.read(&onecharacter, std::streampos(i));

            std::cout << onecharacter;
        }
    }
    else std::cout << "file is not found \n";

    input_file.close();
    std::cin.get();
}

I'd recommend you to read the contents of the file into a buffer (a vector would ease the work for you), and then print the contents. So let's say you set the vector to the size of the file, insert the data into the vector, and then print them out:

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

void main() 
{
    std::string input_file_adress = "res/184672.mp3";
    std::vector<char> vec;
    char onecharacter ;
    std::ifstream input_file(input_file_adress, std::ios::in | std::ios::binary | std::ios::ate);
    
    if (input_file.is_open())
    {
        const int input_file_size = input_file.tellg();
        input_file.seekg(0, std::ios::beg);
        std::cout << "file size - " << input_file_size << std::endl;

        vec.reserve(input_file_size); //set the vector size to the file size.

        //reading input file to vector
        std::copy(std::istream_iterator<char>(input_file),
                 std::istream_iterator<char>(),
                 std::back_inserter(vec));

        //after that print the contents
        for(auto &b: vec)
            std::cout << b;
    }
    else 
        std::cout << "file is not found \n";

    input_file.close();
    std::cin.get();
}

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