Reading From File

Started by
6 comments, last by Dudex 20 years, 11 months ago
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.
Advertisement
On UNIX:
man fscanf

On Windows:
http://msdn.microsoft.com/ -- type in fscanf in the search box
whoops, silly me, I forgot to tell you what i was using lol.

I''m using c++ for this.

Thanks, will do that.
perhaps looking at this will help you in reading files. Here could also be beneficial.
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?
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, sizeof( int ) );<br><br> file.close();<br>} </i>
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.

#define INT_SIZE 4

.....

file.seekg( 0, ios::beg );
file.read( (char *)&myInt, INT_SIZE );

This topic is closed to new replies.

Advertisement