Archived

This topic is now archived and is closed to further replies.

Quick file input question...

This topic is 5573 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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!

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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[i]);
}
fclose(file);


(sorry but I really hate the ugly code format they have on this board)

Share this post


Link to post
Share on other sites
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 elements
std::ifstream fin( filename.c_str() );
 
if( fin.fail() )
return -1; // or false, or whatever''s your preference
while( !fin.eof() )
{
fin >> data;
// if the file is comma-delimited, uncomment the next line:
// fin >> x;
vdata.push_back( data );
}

Share this post


Link to post
Share on other sites