Quick file input question...

Started by
5 comments, last by RegularKid 21 years, 7 months ago
Ok, i have a file that looks like this: "0x70,0x70,0x70,0x01,0x03,0x00,0x20,0x04,0x04,0x00" .....etc. This is how i am reading it in:
  
...
pFileIn = fopen(inFilename.c_str(), "r");

for(int i = 0; i < 10; i++)
{
	fread(&tile, 4, 1, pFileIn);
	printf("0x%08X\n", tile);
}
...
  
However, it''s not getting the correct numbers when I read them in. I read in 4 bytes because it takes four characters per number. I am probably making a simple mistake. Could someone correct me? Thanks!
Advertisement
what type is "tile"?

Don''t listen to me. I''ve had too much coffee.
It''s type int
fread() doesn''t take an int* as its first argument. Its job is to read data, not to convert it to an integer. I suggest you use fscanf instead.

Don''t listen to me. I''ve had too much coffee.
Since you are only loading single int''s one by one, Why not just do this:

--------------
To write:
--------------

int data[5] = { 15, 16, 13, 14, 15 };

FILE *file = NULL;
file = fopen("c:\\windows\\desktop\\test.dat", "wb");
fwrite(data, sizeof(int), 5, file);
fclose(file);

-------------
To read:
-------------

FILE *file = NULL;
file = fopen("c:\\windows\\desktop\\test.dat", "rb");
int data[5];

for (int i = 0; i < 5; i++)
{
fread(&data, sizeof(int), 1, file);
printf("%d\n", data);<br>}<br>fclose(file);<br><br><br>(sorry but I really hate the ugly code format they have &#111;n this board)<br> </i>
Greg Damon
quote:Original post by RegularKid
Ok, i have a file that looks like this:

"0x70,0x70,0x70,0x01,0x03,0x00,0x20,0x04,0x04,0x00" .....etc.

Is the file actually comma delimited? If so, you''re going to need to account for that. Also, is that a hex dump of the file, or does the file actually contain those characters (open it in Notepad, for example, and see what you get)?

If that was a hex dump:
char x;int data;std::vector< int > vdata;  // for unknown number of elementsstd::ifstream fin( filename.c_str() ); if( fin.fail() )  return -1; // or false, or whatever''s your preferencewhile( !fin.eof() ){  fin >> data;  // if the file is comma-delimited, uncomment the next line:  // fin >> x;  vdata.push_back( data );} 
Thanks!

This topic is closed to new replies.

Advertisement