Archived

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

Dudex

Reading From File

Recommended Posts

Hi I never did get how to read from a file. Let''s say I have a binary file called stat.bin In stat.bin it has these following numbers 1212|4355|2314| Each number is seperated. Is there a way for me to get each 4 numbers and say put it into one array so then I can compare these numbers? Thanks.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
On UNIX:
man fscanf

On Windows:
http://msdn.microsoft.com/ -- type in fscanf in the search box

Share this post


Link to post
Share on other sites
The problem is I would like to work with these numbers as integer, instead of characters. Is there a way for me to transfer an integer to a character so then I can compare it since most of these read functions deal with character variables?

Share this post


Link to post
Share on other sites
Here''s some code to get you started. I''m typing this without an actual compiler in front of me, so there may be minor syntactical errors in it.


#include <fstream>

using namespace std;

...


void saveNumbers( int numbers[], int count )
{
fstream file;
file.open( "file.bin", ios::out | ios::trunc | ios::bin );

if( file.fail() )
return;

for( int i=0; i < count ;i++ )
file.write( ( const char *)numbers, sizeof( int ) );

file.close();
}

void readNumbers( int numbers[], count )
{
fstream file;
file.open( "file.bin", ios::in | ios::bin );

if( file.fail() )
return;

for( int i=0; i < count ;i++ )
file.read( ( char *)numbers[i], sizeof( int ) );

file.close();
}

Share this post


Link to post
Share on other sites
Ooo right, why didn''t I think of that duhh hehehe.

However, is there a way to say set the beginning position, get this many bytes and save it to an integer variable?

Thanks.

Share this post


Link to post
Share on other sites