fwrite?

  • Thread starter Thread starter Hilton
  • Start date Start date
H

Hilton

Hi,

I have arrays of ints, float, or doubles etc (e.g. int[], float[], or
double[]), how can I use 'fwrite' and 'fread' to write the array to and read
the array from a file in C# (CF)? I'd prefer not to do any copying etc, so
I'm looking for something like this:

double[] x = new double[]{1.2, 2.3, Math.PI};

unsafe
{
fixed (double *doublePtr = &x[0])
{
byte *ptr = (byte *) doublePtr;

FileStream fs = new FileStream ("\\double.dat",
FileMode.Create);

fs.Write (ptr, 0, x.Length * sizeof(double));

fs.Close ();
}
}

And then have code on the read side doing something like "double[] ptr =
new...; fread (ptr)" (at least the equivalent in C#).

BTW: If you have a non-unsafe solution, that would be excellent!!!

Thanks,

Hilton
 
Here is an example that uses BinaryWriter for writing, and BinaryRead
for reading primitives to/from stream.

double[] x = new double[]{1.2, 2.3, Math.PI};

// save array to file
using(FileStream fs = new FileStream("\\test.dat", FileMode.Create))
{
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(d.Length);
for (int i = 0; i < d.Length; i++)
bw.Write(x);
}


// load array from file
using(FileStream fs = new FileStream("\\test.dat", FileMode.Open))
{
BinaryReader br = new BinaryReader(fs);
int length = br.ReadInt32();
x = new double[length];
for (int i = 0; i < x.Length; i++)
x = br.ReadDouble();
}
 
Back
Top