Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/133.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 逐字节读取二进制istream_C++_Binaryfiles_Istream - Fatal编程技术网

C++ 逐字节读取二进制istream

C++ 逐字节读取二进制istream,c++,binaryfiles,istream,C++,Binaryfiles,Istream,我试图使用ifstream逐字节读取二进制文件。我以前使用过像get()这样的istream方法,一次可以毫无问题地读取二进制文件的整个块。但我当前的任务是逐字节执行,并依赖io系统中的缓冲来提高效率。问题是,我似乎比应该的要早几个字节到达文件末尾。因此,我编写了以下测试程序: #include <iostream> #include <fstream> int main() { typedef unsigned char uint8; std::ifs

我试图使用ifstream逐字节读取二进制文件。我以前使用过像get()这样的istream方法,一次可以毫无问题地读取二进制文件的整个块。但我当前的任务是逐字节执行,并依赖io系统中的缓冲来提高效率。问题是,我似乎比应该的要早几个字节到达文件末尾。因此,我编写了以下测试程序:

#include <iostream>
#include <fstream>

int main() {
    typedef unsigned char uint8;
    std::ifstream source("test.dat", std::ios_base::binary);
    while (source) {
        std::ios::pos_type before = source.tellg();
        uint8 x;
        source >> x;
        std::ios::pos_type after = source.tellg();
        std::cout << before << ' ' << static_cast<int>(x) << ' '
                  << after << std::endl;
    }
    return 0;
}
#包括
#包括
int main(){
typedef无符号字符uint8;
std::ifstream源(“test.dat”,std::ios\u base::binary);
while(来源){
std::ios::pos_type before=source.tellg();
uint8x;
来源>>x;
std::ios::pos_type after=source.tellg();

std::cout有一个成员函数,您可以在其中指定字节数。

为什么要使用格式化提取,而不是
.read()

将给您一个字节。它是无格式的输入函数。
运算符>是格式化的输入函数,可能意味着跳过空白字符。

如其他提到的,您应该使用。但是,如果必须使用格式化的提取,考虑.< /p> < p> >提取器用于格式化输入; 默认)。对于单字符无格式输入,可以使用 (返回一个
int
,如果读取失败则返回EOF,或者 范围为[0,UCHAR_MAX])或
istream::get(char&)
(将 参数中读取的字符,返回转换为
bool
,如果读取成功则为true,如果读取失败则为false。

因为
source>>x;
source.read(reinterpret\u cast(&x));
更容易读取,而且我不希望二进制文件中单个字节的提取运算符能够进行任何格式化。
.get()
可能比
read()更有效
用于单个字节。但实现可能有
.read
调用
.get
调用,反之亦然。source.read((char*)&x)是更短的,C样式转换的意思与本例中的reinterpret cast相同。@cubuspl42:最好避免养成使用任何C样式转换的习惯,虽然哇,但我的想法是,如果没有某种类型的转换,我无法从二进制文件中读取一个字节。这是因为流是为文本设计的(即使以二进制模式打开时也是如此)。通常,在读取实际二进制日期时,我将使用系统级例程(Unix下的open/read/write/close),而不必使用iostream。仍然可以使用std::skipws,以便流跳过空白(和其他格式)即使与流一起使用operators@Ghita我想你的意思是
std::noskipws
。很抱歉,在这种情况下你不想跳过空格不,我实际上是指noskipws。我的意思是你仍然可以使用formattedd提取(使用流运算符),只是在这种情况下必须指定skipws
source.get()