c#中的cread c ++。我知道我需要字节缓冲但不是那里

时间:2018-05-31 12:35:28

标签: c# c++

嘿大家我是面向对象编程的新手,我试图将一些c ++代码转移到c#中。我想翻译:

fread(top,sizeof(int),16,stream);
first = top[1];
second = top[2];

依旧.....

其中top是:static int top [16];

流文件是.eng文件,我想将其转换为.csv文件。所以我想阅读.eng文件进行转换。

我目前有

if (fs.CanRead)
        {
            byte[] buffer = new byte[fs.Length]; 
            int bytesread = fs.Read(buffer, 0, buffer.Length);
            char[] CharTest = (Encoding.ASCII.GetChars(buffer, 0, bytesread));
            string bytesString = Encoding.ASCII.GetString(buffer, 0, bytesread); 
            Console.WriteLine(CharTest);
            //Console.WriteLine(bytesString);

            byte[] top = new byte[16];
            first = top[1];

所以我能够读取我的fs文件,并将charTest作为整个.eng文件。虽然在c ++线上它被分成16个顶部。我不明白c ++是如何做到这一点的。我主要对sizeof(int)部分感到困惑。我有能力阅读整个文件,但不知道在哪里分开以获得16并构建顶部数组

2 个答案:

答案 0 :(得分:0)

以下是有关fread的一些文档:

http://en.cppreference.com/w/cpp/io/c/fread

因此,fread的第一个参数是内存中将读取文件的位置。第二个是从文件中读取的每个对象的大小(以字节为单位),第三个是对象的数量。最后一个是流。

例如,fread(buffer, sizeof(double), 12, stream)表示从流到缓冲区中读取大小为double的12个对象。

static int header[16];表示包含内部链接的16个整数数组(最后一部分不一定是您在此阶段需要关注的内容)。

答案 1 :(得分:0)

我要写的代码是:

using (var fs = File.OpenRead("somefile.eng"))
using (var br = new BinaryReader(fs))
using (var csv = new StreamWriter("output.csv", false, Encoding.ASCII))
{
    // Note that the array is useless, because we write the csv
    // one int at a time!
    int[] row = new int[16];

    while (true)
    {
        // used for skipping the ; at before the first element
        bool first = true;

        // Note that the file must be composed of only
        // blocks of 16 int32 . No dangling byte
        for (int i = 0; i < 16; i++)
        {
            row[i] = br.ReadInt32();

            // You are skipping top[0]
            if (i == 0)
            {
                continue;
            }

            // No ; before the first element
            if (first)
            {
                first = false;
            }
            else
            {
                csv.Write(';');
            } 

            csv.Write(row[i]);
        }

        // End of file
        if (br.PeekChar() == -1)
        {
            break;
        }

        csv.WriteLine();
    }
}

有一个非常好的BinaryReader类可用于从Stream(在本例中为文件)中读取二进制数据。然后,您可以使用StreamWriter类编写csv。

通常在这一点上我会抛出一个关于Encoding.ASCII的长篇大论以及关于手动编写CSV文件而不是使用库的问题,但这只是一个只有数字的CSV,那么这对于它来说并不是一件坏事。按照书面记录。