Reading a single byte from file.

Hi,
I am having an issue with reading a single byte from a file.
I want to read a byte from a file and set a NumericUpDown controls' value to the byte that was read from the file. Below is the code I have.
Thanks.


1
2
3
4
5
6
  		fstream inFile(File_Path_Music, ios::in | ios::out | ios::binary);
		char buffer[1];
		inFile.seekg(0xA8C7C); // Theme
		inFile.read(buffer, 1);
		inFile.close();
		NumericUpDow1->Value = buffer[1];


I have a horizontal control that sets the value of the NumericUpDown1 control. This value is written to the file.
It works from 0 to ~100 or so but anything higher I don't get the correct number in NumericUpDwon1 control. When setting the Horizontal control to 255 I get a -1 value when I read it from the file.

Any ideas?

NumericUpDow1->Value = (unsigned char)(buffer[0]) ;
Last edited on
Line 6 is assigning the 2nd element of a 1 char array to the control. You are assigning a value not read from the file, going out of bounds of the array, retrieving whatever bogus value at a memory location outside of the array.

Remember, in C/C++ an array's first element is looked up with operator[0], as JLBorges shows.
Remember, in C/C++ an array's first element is looked up with operator[0], as JLBorges shows.


Yes I know. I forgot to change it back to 0 when I posted. however it still got the wrong value using 0 or 1...

What solved the issue was using (unsigned char) in brackets. hmm never encountered this error before... is that type casting?

https://stackoverflow.com/questions/75191/what-is-an-unsigned-char


Thanks for the help. :)
> What solved the issue was using (unsigned char) in brackets.
> hmm never encountered this error before... is that type casting?

The type char may be (in this case is) a signed integral type.
So the cast is required if we want to interpret its value as an unsigned integer value.

It is a C-style cast (an explicit type conversion).

Any of these cast expressions would suffice:
1
2
3
4
5
6
7
8
char c = char(255) ;

int i = (unsigned char)c ; // c-style cast

using uchar_t = unsigned char ;
i = uchar_t(c) ; // functional-style cast

i = static_cast<unsigned char>(c) ; // static cast 


Pedants believe that the static cast is the the 'correct' cast.
Last edited on
Topic archived. No new replies allowed.