0

The binary file was written for a C++ application and it reads the file as chunks of objects. For e.g.,

class Reader {
    int id;
    int ratio;
    int space;
    float depth;
    double width;
}

Now the binary file is being read as.

 vector <Reader> vectorLists;
    FILE * pFile;
       Reader rd;

       pFile = fopen ("reader.dat" , "r");
 for ( /*until end of file, goes in a loop*/) { 
       if (pFile == NULL) perror ("Error opening file");
       else {
         if ( fgets (rd, sizeof(Reader) , pFile) != NULL )
          vectorLists.push_back(rd);
       } 
   }

Here it's reading a chunk of data based on the size of Reader class and assign that to a Reader object. Then this object is added to an array of Reader objects in a vector.

The task is to do the same in C#. i.e., how to read the same way into a C# class object? I know how to read a text file, but reading a binary as class objects is beyond my comprehension.

jazb
  • 5,498
  • 6
  • 37
  • 44
donguy76
  • 610
  • 3
  • 12
  • 33
  • Parsing Binary is hard. Parsing string would be noticeably less hard. But ideally you want some well developed autoamtic do this for you. CSV and XML are two very common string based and automation friendly formats. If you start reading raw binary you ahve to deal with Endianess and all the other stuff of encodings, wich is usually not worth the effort. Best to know wich droid can deal with doing this for you. – Christopher Jul 31 '19 at 23:31
  • 3
    you can use [`BinaryReader`](https://learn.microsoft.com/en-us/dotnet/api/system.io.binaryreader) to read the values – Slai Jul 31 '19 at 23:42
  • Can you use structs, or the code has some class specific aspects? – Sohaib Jundi Aug 01 '19 at 02:06
  • See also https://stackoverflow.com/questions/4908205/idiomatic-c-sharp-deserialization-of-custom-binary-files and https://stackoverflow.com/questions/4154230/can-i-use-c-sharp-serialization-to-read-a-binary-file-in-custom-format – Peter Duniho Aug 01 '19 at 05:28

0 Answers0