Fread C++ in C#.我知道我需要字节缓冲区,但并不完全在那里

fread c++ in c#. I know I need byte buffer but not quite there

本文关键字:缓冲区 在那里 不完全 字节 in C++ 我知道 Fread      更新时间:2023-10-16

大家好,我是面向对象编程的新手,我正在尝试将一些 c++ 代码转换为 c#。 我正在尝试翻译:

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

等等.....

其中 top 是: 静态 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++ 是如何做到这一点的。 我主要对大小(int(部分感到困惑。 我有能力读取整个文件,但不确定在哪里分离以获得 16 并构建顶部数组

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

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

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

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

static int header[16];表示具有内部链接的 16 个整数数组(最后一部分不一定是现阶段您需要关心的(。

我会写的代码是:

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,那么按照所写的方式做并不是一件坏事。