Best way to read binary file c++ though input redirection

前端 未结 1 1147
刺人心
刺人心 2020-12-19 13:30

I am trying to read a large binary file thought input redirection (stdin) at runtime, and stdin is mandatory.

./a.out < input.b         


        
相关标签:
1条回答
  • 2020-12-19 14:08

    If it were me I would probably do something similar to this:

    const std::size_t INIT_BUFFER_SIZE = 1024;
    
    int main()
    {
        try
        {
            // on some systems you may need to reopen stdin in binary mode
            // this is supposed to be reasonably portable
            std::freopen(nullptr, "rb", stdin);
    
            if(std::ferror(stdin))
                throw std::runtime_error(std::strerror(errno));
    
            std::size_t len;
            std::array<char, INIT_BUFFER_SIZE> buf;
    
            // somewhere to store the data
            std::vector<char> input;
    
            // use std::fread and remember to only use as many bytes as are returned
            // according to len
            while((len = std::fread(buf.data(), sizeof(buf[0]), buf.size(), stdin)) > 0)
            {
                // whoopsie
                if(std::ferror(stdin) && !std::feof(stdin))
                    throw std::runtime_error(std::strerror(errno));
    
                // use {buf.data(), buf.data() + len} here
                input.insert(input.end(), buf.data(), buf.data() + len); // append to vector
            }
    
            // use input vector here
        }
        catch(std::exception const& e)
        {
            std::cerr << e.what() << '\n';
            return EXIT_FAILURE;
        }
    
        return EXIT_SUCCESS;
    }
    

    Note you may need to re-open stdin in binary mode not sure how portable that is but various documentation suggests is reasonably well supported across systems.

    0 讨论(0)
提交回复
热议问题