Domanda

I have C# code below:

FileStream fs       = new FileStream("output.bin", FileMode.Open);
BinaryReader _br    = new BinaryReader(fs);
var a               = _br.ReadByte();
var b               = _br.ReadByte();
fs.Close();

a returns 0x00 and b returns 0x03.

But in my C++ code:

std::ifstream ifs("output.bin", std::ios::binary);;
char buf1[2];
ifs.read(buf1, 2);

buf1[0] returns -52 and buf1[1] returns -52.

What's wrong with my code?

È stato utile?

Soluzione

You need to check that state of your stream in the C++ code after creation, and after the read, to be sure that the operations were successful. Ie if (ifs) {...} after creating the stream, and after reading it. If either operations failed, then after you are just reading uninitialised / undefined data from buf1.

See http://www.cplusplus.com/reference/istream/istream/read/ for examples of using ifstream properly.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top