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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.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++ ifstream提取操作符不工作_C++_Iostream - Fatal编程技术网

C++ ifstream提取操作符不工作

C++ ifstream提取操作符不工作,c++,iostream,C++,Iostream,我正在尝试使用以下代码从二进制文件读取数据: fstream s; s.open(L"E:\\test_bin.bin", ios::in | ios::binary); int c = 0; while (!s.eof()) { s >> c; cout << c; } fss; s、 打开(L“E:\\test_bin.bin”,ios::in | ios::binary); int c=0; 而(!s.eof()) { s>>c; cout使用io

我正在尝试使用以下代码从二进制文件读取数据:

fstream s;
s.open(L"E:\\test_bin.bin", ios::in | ios::binary);
int c = 0;
while (!s.eof())
{
    s >> c;
    cout << c;
}
fss;
s、 打开(L“E:\\test_bin.bin”,ios::in | ios::binary);
int c=0;
而(!s.eof())
{
s>>c;

cout使用
ios::binary
标志并不一定意味着您可以读取和写入二进制数据。请看。
ios::binary
表示“读取或写入数据时不进行翻译…”

您可能想做的是使用
s.read(…)
。在您的例子中,流操作符尝试读取一个完整的整数(类似于“1234”)而不是X个适合整数的位数

对于读取4个字节,类似于folling的功能可能会起作用(未测试):

有什么问题吗

int c = 0;
char ch;
int shift = 32;
while ( s.get( ch ) && shift != 0 ) {
    shift -= 8;
    c |= (ch & 0xFF) << shift;
}
if ( shift != 0 ) {
    //  Unexpected end of file...
}
intc=0;
char ch;
int-shift=32;
而(s.get(ch)和shift!=0){
移位-=8;

c |=(ch&0xFF)在打开文件后放置一个if以检测错误(也
,而(!s.eof())
是错误的)从二进制文件读入后,您希望“c”包含什么?一块位或一个完整的数字?它仍然不读取任何内容,但正如我提到的,文件正常并成功打开。当然是一块位。可能是重复的,我需要读取完整的4个字节。您的意思是我不能使用>>从文件中读取字节?“数据在没有翻译的情况下读取或写入…”是二进制流的定义,这当然是不正确的。循环应该是
while(s.read((char*n)&n,4)和&s.gcount()!=0){}
。除了它仍然只是将原始字节读入
int
,这是永远不对的。@JamesKanze谢谢,我有点太仓促了。@user657267始终会创建一个
sentry
对象,即使对于
s.read
。区别在于
(除非目标是
streambuf*
),sentry参数使用来自
ios_base
skipws
标志初始化;对于非格式化输入,它使用常量
noskipws
初始化,而不管
ios_base
中标志的状态如何。这不是以大端格式读取int吗?@james在大多数网络协议中,int是大端的这几乎是一个标准。(在某种程度上,这相当令人惊讶,因为大多数早期协议都是在DEC处理器上开发的,而DEC处理器是小端的。)
int c = 0;
char ch;
int shift = 32;
while ( s.get( ch ) && shift != 0 ) {
    shift -= 8;
    c |= (ch & 0xFF) << shift;
}
if ( shift != 0 ) {
    //  Unexpected end of file...
}