[英]Best way to read binary file c++ though input redirection
我試圖在運行時讀取一個大的二進制文件思想輸入重定向( stdin
),並且stdin
是必需的。
./a.out < input.bin
到目前為止,我已經使用了fgets。 但是fgets會跳過空白和換行。 我想包括兩者。 我的currentBuffersize
可以動態變化。
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;
}
提前致謝。
如果是我,我可能會做類似的事情:
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;
}
請注意,您可能需要在二進制模式下重新打開stdin
,不確定各種文檔建議的可移植性是否在各系統中得到了相當好的支持。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.