You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中BinaryReader无法读取BinaryWriter存入dat文件的数据该如何正确实现?

问题原因

  • numOfStudents是实例级变量,每次新建BinaryTesting对象时都会被重置为0,最后调用读取方法的对象仅记录了1个学生,循环读取次数错误
  • 读取逻辑错位:学生姓名仅在循环外读取了一次,第二个学生的姓名字段二进制内容被当作int类型读取,出现异常乱码数值
  • 主函数总分变量totMarks没有在每次录入学生前重置,计算出的平均分错误
  • 文件流读写没有使用安全的自动释放逻辑,存在资源占用风险

修正后完整代码

using System;
using System.IO;

namespace BinaryWriterDemo
{
    class BinaryTesting
    {
        string studentName;
        int[] studentMarks = new int[3];
        int avgMarks;
        public BinaryTesting(string studentName, int[] studentMarks, int avgMarks)
        {
            this.studentName = studentName;
            this.studentMarks = studentMarks;
            this.avgMarks = avgMarks;
        }
        public void WriteData()
        {
            // using块自动释放资源,不需要手动调用Close
            using FileStream fs = new FileStream(@"/Users/swapnilnawale/Desktop/stud.dat", FileMode.Append, FileAccess.Write);
            using BinaryWriter bw = new BinaryWriter(fs);
            bw.Write(studentName);
            for(int i = 0; i<3;i++)
            {
                bw.Write(studentMarks[i]);
            }
            bw.Write(avgMarks);
        }
        public void ReadData()
        {
            using FileStream fs = new FileStream(@"/Users/swapnilnawale/Desktop/stud.dat", FileMode.Open, FileAccess.Read);
            using BinaryReader br = new BinaryReader(fs);
            // 自动判断文件是否读完,不需要依赖统计的学生数量
            while (br.PeekChar() > -1)
            {
                // 每个学生的姓名都要单独读取
                string curName = br.ReadString();
                Console.Write(curName + "\t");
                for (int i = 0; i < 3; i++)
                {
                    int mark = br.ReadInt32();
                    Console.Write(mark + "\t");
                }
                int curAvg = br.ReadInt32();
                Console.WriteLine(curAvg);
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            string studentName;
            int[] studentMarks = new int[3];
            int i = 0, totMarks=0, avgMarks;
            string resp;
            BinaryTesting bt = null;
            do
            {
                // 每次录入新学生前重置总分
                totMarks = 0;
                i++;
                Console.Write("Enter Student {0} Name: ", i);
                studentName = Console.ReadLine();
                
                for(int j = 0; j<3;j++)
                {
                    Console.Write("Enter Student {0} Subject {1} Marks: ", i, (j+1));
                    studentMarks[j]=Convert.ToInt32(Console.ReadLine());
                    totMarks += studentMarks[j];
                }
                avgMarks = totMarks / 3;
                bt = new BinaryTesting(studentName, studentMarks, avgMarks);
                bt.WriteData();
                Console.WriteLine("Press Y to continue");
                resp = Console.ReadLine();
            } while (resp == "Y" || resp == "y");
            bt.ReadData();
        }
    }
}

内容的提问来源于stack exchange,提问作者Swapnil Nawale

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 01:27:03