簡體   English   中英

在C#中讀取二進制大小未知的文件

[英]reading a binary unknown size file in c#

我剛剛從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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM