在c#中读取未知大小的二进制文件

reading a binary unknown size file in c#

本文关键字:二进制文件 未知 读取      更新时间:2023-10-16

我刚刚从c++切换到c#。我已经用c++完成了一些任务,现在我必须用c#进行翻译。

我正在处理一些问题。

我必须找到二进制文件中符号的频率(这是唯一的参数,所以不知道它的大小/长度)。(这些频率将进一步用于创建huffman tree)。

我在c++中的代码如下:

我的结构是这样的:

struct Node     
{    
    unsigned int symbol;
    int freq;    
    struct Node * next,  * left, * right;  
};
Node * tree;

我如何读取文件是这样的:

FILE * fp;
fp = fopen(argv, "rb");
ch = fgetc(fp);
while (fread( & ch, sizeof(ch), 1, fp)) {
    create_frequency(ch);
}
fclose(fp);

有谁能帮我翻译相同的c#(特别是这个二进制文件读取过程创建符号的频率和存储在链表)?谢谢你的帮助

编辑:尝试根据Henk Holterman下面解释的代码编写,但仍然存在错误,错误是:

error CS1501: No overload for method 'Open' takes '1' arguments
/usr/lib/mono/2.0/mscorlib.dll (Location of the symbol related to previous error)
shekhar_c#.cs(22,32): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration
Compilation failed: 2 error(s), 0 warnings

我的代码是:

static void Main(string[] args)
{
    // using provides exception-safe closing
    using (var fp = System.IO.File.Open(args))
    {
        int b; // note: not a byte
        while ((b = fp.Readbyte()) >= 0)
        {
            byte ch = (byte) b;
            // now use the byte in 'ch'
            //create_frequency(ch);
        }
    }
 }

两个错误对应的行是:

using (var fp = System.IO.File.Open(args))
有人能帮帮我吗?我是c#初学者
string fileName = ...
using (var fp = System.IO.File.OpenRead(fileName)) // using provides exception-safe closing
{
    int b; // note: not a byte
    while ((b = fp.ReadByte()) >= 0)
    {
        byte ch = (byte) b;
        // now use the byte in 'ch'
        create_frequency(ch);
    }
}