Advertisement

fstream question

Started by September 26, 2002 04:27 AM
2 comments, last by werdy666 22 years, 1 month ago
hi, i am loading in a binary file into a 2d vector. i have it working but don't understand how it works! lol here is the code....

int widthb[1];
int heightb[1];
int value1[1];

vector  > mapdata;

int LoadMapData()
{
	ifstream load;
	load.open("test.map", ios::binary);
	if (load.fail())
		return false;
	load.read((char*)widthb, 2);
	load.read((char*)heightb,2);
	mapxsize = *widthb;
	mapysize = *heightb;
	// this is to determine how big the map is.

	mapdata.resize(mapxsize);
		for (int i = 0; i < mapxsize; i++) 
			{
			mapdata.resize(mapysize);
			for (int j = 0; j < mapysize; j++) 
				{
				load.read((char*)value1, 1);
				
				mapdata[j] = *value1;
				}
			}
	load.close();

</pre> 

when i declare value1 as "int value1[1]" if i don't add the little array bit at the end it will not load the correct value when i use the load.read(), but i don't understand why. could someone please explain it to me???? or point me to a site that will help me understand it better? Also if anyone can explain why i have had to use pointers in this code, i can use them a little, but do not understand them yet!:mad:  lol

Thanks for any help u can give….

   </i>     </pre>  

Werdy666 <img src="smile.gif" width=15 height=15 align=middle>

<SPAN CLASS=editedby>[edited by - werdy666 &#111;n September 26, 2002 5:41:42 AM]</SPAN>    
You can change the variables back to regular integers if you use the & operator:

load.read((char*)&widthb, 2);
Advertisement
fstream (good) or fstream.h (bad) ?
link


Documents [ GDNet | MSDN | STL | OpenGL | Formats | RTFM | Asking Smart Questions ]
C++ Stuff [ MinGW | Loki | SDL | Boost. | STLport | FLTK | ACCU Recommended Books ]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
The reason that it works with the arrays, is that when you define an array (Eg. int widthb[1]), widthb is essentially a pointer to an intereger (the first in the array).

The fstream read operation must be given a pointer or reference to the memory it is to write to. So, in essence, you were unknowingly providing it with a pointer.

Probably a better way to do it is to either decalre
int *widthb;
load.read((char*)widthb, sizeof(int));

OR

int widthb;
load.read((char*)&widthb, sizeof(int));

Note that it is usually easier to use the ''sizeof(datatype)'' function to determine the number of bytes to read, rather than hardcoding a number there. You will find this espescially when you come to reading things like structs from files.

This topic is closed to new replies.

Advertisement