Reputation: 31
I found a C# source code that read from file which have 1000000 double number. The source code is below.
public void filereader()
{
using (BinaryReader b = new BinaryReader(File.Open("C:\\Users\\Hanieh\\Desktop\\nums.txt", FileMode.Open)))
{
int length = (int)b.BaseStream.Length;
byte[] fileBytes = b.ReadBytes(length);
for (int ii = 0; ii < fileBytes.Length - 32 ; ii++)
{
savg1[ii / 2] = (double)(BitConverter.ToInt16(fileBytes, ii) / 20000.0);// inja error index midee
ii++;
}
}
}
when I run source code to read from text file I have an error that related to savg1 index that is out of bound. I debug step by step and result shows size of length= 24000000 but savg1=1000000. my question is here: how this source code work and how I can fix this problem.
Upvotes: 1
Views: 314
Reputation: 186668
I suggest something like this (File.ReadAllBytes
and BitConverter.ToDouble
):
byte[] source = File.ReadAllBytes(@"C:\Users\Hanieh\Desktop\nums.txt");
double[] data = new double[source.Length / sizeof(double)];
for (int i = 0; i < data.Length; ++i)
data[i] = BitConverter.ToDouble(source, i * sizeof(double));
Upvotes: 1
Reputation: 22038
I would solve it like:
double[] data;
using (BinaryReader b = new BinaryReader(File.Open("C:\\Users\\Hanieh\\Desktop\\nums.txt", FileMode.Open)))
{
// create array/buffer for the doubles (filelength / bytes per double)
data = new double[b.BaseStream.Length / sizeof(double)];
// read the data from the binarystream
for (int i = 0; i < data.Length; i++)
data[i] = b.ReadDouble();
}
MessageBox.Show("doubles read: " + data.Length.ToString());
Although, your file nums.txt implies that it is a textfile. You might not read it as a binary file.
Upvotes: 0