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);
}
}
reading a binary unknown size file in c#
-
12-06-2023 - |
Вопрос
I have just switched to c# from c++. I have already done some task in c++ and the same now i have to translate in c#.
I am going through some problems.
I have to find the frequency of symbols in binary files (which is taken as sole argument, so don't know it's size/length).(these frequency will be further used to create huffman tree
).
My code to do that in c++ is below :
My structure is like this:
struct Node
{
unsigned int symbol;
int freq;
struct Node * next, * left, * right;
};
Node * tree;
And how i read the file is like this :
FILE * fp;
fp = fopen(argv, "rb");
ch = fgetc(fp);
while (fread( & ch, sizeof(ch), 1, fp)) {
create_frequency(ch);
}
fclose(fp);
Could any one please help me in translating the same in c# (specially this binary file read procedure to create frequency of symbols and storing in linked list)? Thanks for the help
Edit: Tried to write the code according to what Henk Holterman explained below but still there is error and the error is :
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
And my code to do this is:
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);
}
}
}
And the line corresponding to the two errors is :
using (var fp = System.IO.File.Open(args))
could some one please help me ? I am beginner to c#
Решение