Author Topic: Problem in saving/reading arrays with File Object  (Read 5856 times)

Offline OriolLehmkuhl

  • PixInsight Addict
  • ***
  • Posts: 177
    • http://www.astrosurf.com/brego-sky
Problem in saving/reading arrays with File Object
« on: 2008 September 28 05:44:09 »
Hi folks!

We have been trying to use the File Object to save arrays without success  :? This is our test code:

Code: [Select]

#include <pjsr/DataType.jsh>
#define N 10

function main()
{
   console.hide();
   var fo = new File;
   var userArray = new Array(N);
   for(var i=0;i<userArray.length;i++) {
        userArray[i] = i ;
   }
   fo.createForWriting("/home/oriol/testFile.dat");
   fo.write(userArray,DataType_Int32);
   fo.close();


   var fi = new File;
   var userArray2 = new Array(N);
   fi.openForReading("/home/oriol/testFile.dat");
   
   userArray2 = fi.read(DataType_Int32,N);
   for(var i=0;i<userArray2.length;i++) {
        console.writeln("position "+i+" value "+userArray2[i]+"\n");
   }
}

main();


If the macro N is changed to 1, the saved array is not well read (in fact, the length of the read array is 0  :? ) What is wrong in our test?

Regards

Offline Juan Conejero

  • PTeam Member
  • PixInsight Jedi Grand Master
  • ********
  • Posts: 7111
    • http://pixinsight.com/
Problem in saving/reading arrays with File Object
« Reply #1 on: 2008 September 28 06:55:19 »
Hi Oriol,

When File.read() reads only one item, it doesn't return it as an array, but as a single object. This happens because the prototype of File.read() is:

Code: [Select]
Object File.read( int dataType[, int count=1] )

Note that the count argument is optional. When count is not specified, count=1 is assumed.

Try with this version of your code, which works as expected:

Code: [Select]
#include <pjsr/DataType.jsh>

#define N 10

function main()
{
   var userArray = new Array( N );
   for ( var i = 0; i < N; ++i )
      userArray[i] = i;

   var fo = new File;
   fo.createForWriting( "/home/juan/testFile.dat" );
   fo.write( userArray, DataType_Int32 );
   fo.close();

   var fi = new File;
   fi.openForReading( "/home/juan/testFile.dat" );

   var userArray2;
   var maybeUserArray = fi.read( DataType_Int32, N );
   if ( maybeUserArray instanceof Array )
      userArray2 = maybeUserArray;
   else
   {
      userArray2 = new Array( 1 );
      userArray2[0] = maybeUserArray;
   }
 
   for( var i = 0, n = userArray2.length; i < n; ++i )
      console.writeln( "position ", i, " value ", userArray2[i] );

   console.show();
}

main();


(you'll have to change /home/juan by /home/oriol). This code works for N = 1.
Juan Conejero
PixInsight Development Team
http://pixinsight.com/

Offline OriolLehmkuhl

  • PixInsight Addict
  • ***
  • Posts: 177
    • http://www.astrosurf.com/brego-sky
Problem in saving/reading arrays with File Object
« Reply #2 on: 2008 September 28 09:49:13 »
Thanks Juan, now the code works as expected  :wink:

Regards