Link to home
Start Free TrialLog in
Avatar of Cryptos
Cryptos

asked on

how to determine the length of a file

Im opening a file which length I dont know, but want read all the datas in there, here my code:

const char* infile;
infile="test.dat";
vector<double> key;
int size=0;

FILE *fp1;

fp1=fopen(infile, "r");

//HERE I NEED THE SIZE OF THE FILE

while( !feof( stream ) ){size++;}
//this gives an unending loop!!


key.resize(size);

for (int k=0; k<size; k++){
     fscanf(fp1, "%lf\n", &key[k]);
}
 
fclose(fp1);

return key;




Any suggestions?

Thanks

Urs
ASKER CERTIFIED SOLUTION
Avatar of Kimpan
Kimpan
Flag of Sweden image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Cryptos
Cryptos

ASKER

of course stream in the while loop is not stream, its fp. But this gives still an infinite loop!

greets U
Avatar of Cryptos

ASKER

How would the code look with this fseek?? And how do I move back to the begining to start the scan again??

Thanks

U
Avatar of jkr
>>//HERE I NEED THE SIZE OF THE FILE

struct _stat st;

fstat ( fp1, &st);

// 'size' can be found as st.st_size
Avatar of Cryptos

ASKER

jkr:

header??

Im working with MSVC6.

thanx

U
[1] open the file
[2] use fseek() to move the pointer at the end of the file
[3] use ftell() to get the position, which is the length of the file
Avatar of Cryptos

ASKER

jkr:

header found. But the problem is still: It doesnt compile, at the _fstat(...) function takes an int as first argument and not my *iobuf.
So I use the oldcast _open() function? therefore I must know the number of bytes in the file. In fact there are doubles ints and so on...

mhhh

tanx
U
#include <sys/stat.h>
#include <sys/types.h>

The VC++ docs on '_fstat()' are mentioning that :o)
Avatar of Cryptos

ASKER

The thing works fine.

Thanks

U