Best way to read binary file c++ though input redirection(通过输入重定向读取二进制文件 c++ 的最佳方法)
问题描述
我试图在运行时读取一个大型二进制文件,认为输入重定向 (stdin),并且 stdin 是强制性的.
I am trying to read a large binary file thought input redirection (stdin) at runtime, and stdin is mandatory. 
./a.out < input.bin
到目前为止我已经使用过 fgets.但是 fgets 会跳过空格和换行符.我想包括两者.我的 currentBuffersize 可以动态变化.
So far I have used fgets. But fgets skips blanks and newline. I want to include both. My currentBuffersize could dynamically vary.
FILE * inputFileStream = stdin; 
int currentPos = INIT_BUFFER_SIZE;
int currentBufferSize = 24; // opt
unsigned short int count = 0; // As Max number of packets 30,000/65,536
while (!feof(inputFileStream)) {
    char buf[INIT_BUFFER_SIZE]; // size of byte
    fgets(buf, sizeof(buf), inputFileStream);
    cout<<buf;
    cout<<endl;
}
提前致谢.
推荐答案
如果是我,我可能会做类似的事情:
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() << '
';
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}
请注意,您可能需要以二进制模式重新打开stdin,不确定它的可移植性如何,但各种文档表明跨系统的支持相当好.
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.
这篇关于通过输入重定向读取二进制文件 c++ 的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:通过输入重定向读取二进制文件 c++ 的最佳方法
				
        
 
            
        基础教程推荐
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
 - 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
 - 常量变量在标题中不起作用 2021-01-01
 - 如何通过C程序打开命令提示符Cmd 2022-12-09
 - 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 - 我有静态或动态 boost 库吗? 2021-01-01
 - C++结构和函数声明。为什么它不能编译? 2022-11-07
 - 这个宏可以转换成函数吗? 2022-01-01
 - 在 C++ 中计算滚动/移动平均值 2021-01-01
 - 如何检查GTK+3.0中的小部件类型? 2022-11-30
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				