Home   Cover Cover Cover Cover

Binäre Dateien

using System;
using System.IO;

class Point {
  public double x, y;
  public Point(double a, double b) { x = a; y = b; }

// Writes an array of points to a binary file and reads it in again
public class BinaryFiles {
  static void Main(string[] arg) {
    Point[] points = {new Point(1.0,3.2), new Point(0.4,2.9), new Point(4.3,9.2)};
    //--- writing the points
    FileStream s = new FileStream("data", FileMode.Create);
    BinaryWriter w = new BinaryWriter(s);
    foreach (Point p in points) {
      w.Write(p.x); w.Write(p.y);
    w.Close(); s.Close();
    //--- reading the points
    s = new FileStream("data", FileMode.Open);
    BinaryReader r = new BinaryReader(s);
    int len = r.ReadInt32();
    points = new Point[len];
    for (int i = 0; i < len; i++) {
      double x = r.ReadDouble();
      double y = r.ReadDouble();
      points[i] = new Point(x, y);
    r.Close(); s.Close();
    //--- test output on the screen
    foreach (Point p in points)
      Console.WriteLine("({0},{1})", p.x, p.y);