1

I have been assigned to convert a C++ app to C#.

I want to convert the following code in C# where rate_buff is a double[3,9876] two dimensional array.

if ((fread((char*) rate_buff,
                            (size_t) record_size,
                            (size_t) record_count,
                            stream)) == (size_t) record_count)
2
  • and your question is? Commented Jul 18, 2013 at 16:23
  • Need to convert the above code into C#. Commented Jul 18, 2013 at 16:25

1 Answer 1

5

If I correctly guessed your requirements, this is what you want:

int record_size = 9876;
int record_count = 3;

double[,] rate_buff = new double[record_count, record_size];

// open the file
using (Stream stream = File.OpenRead("some file path"))
{
    // create byte buffer for stream reading that is record_size * sizeof(double) in bytes
    byte[] buffer = new byte[record_size * sizeof(double)];

    for (int i = 0; i < record_count; i++)
    {
        // read one record
        if (stream.Read(buffer, 0, buffer.Length) != buffer.Length)
            throw new InvalidDataException();

        // copy the doubles out of the byte buffer into the two dimensional array
        // note this assumes machine-endian byte order
        for (int j = 0; j < record_size; j++)
            rate_buff[i, j] = BitConverter.ToDouble(buffer, j * sizeof(double));
    }
}

Or more concisely with a BinaryReader:

int record_size = 9876;
int record_count = 3;

double[,] rate_buff = new double[record_count, record_size];

// open the file
using (BinaryReader reader = new BinaryReader(File.OpenRead("some file path")))
{
    for (int i = 0; i < record_count; i++)
    {
        // read the doubles out of the byte buffer into the two dimensional array
        // note this assumes machine-endian byte order
        for (int j = 0; j < record_size; j++)
            rate_buff[i, j] = reader.ReadDouble();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.