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

时间:2014-03-10 10:05:07

标签: c# c++ algorithm binaryfiles huffman-code

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

我正在经历一些问题。

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

我在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#

的初学者

1 个答案:

答案 0 :(得分:3)

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