1

我已被分配将 C++ 应用程序转换为 C#。

我想在 C# 中转换以下代码,其中 rate_buff 是一个 double[3,9876] 二维数组。

if ((fread((char*) rate_buff,
                            (size_t) record_size,
                            (size_t) record_count,
                            stream)) == (size_t) record_count)
4

1 回答 1

5

如果我猜对了您的要求,这就是您想要的:

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));
    }
}

或者更简洁地使用 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();
    }
}
于 2013-07-18T16:37:20.677 回答