【发布时间】:2016-02-14 00:50:11
【问题描述】:
我正在尝试使用下面的代码从带有 while 循环的二进制文件中读取,但由于某种原因,循环在最后一个条目后没有中断。共有 4 个条目,每个条目位于一行中,每一行的格式如下。
StudentID StudentName StudentSurname StudentEmail StudentYear GPA
创建过滤器文件的功能。
public bool createGPAFilterFile(string fileName, string GPAFilterFileName, double lowerGPA, double upperGPA){
try
{
MainClass sideObj = new MainClass();
sideObj.createBinaryFile(GPAFilterFileName);
FileStream stream = File.Open(fileName, FileMode.Open);
BinaryReader reader = new BinaryReader(stream);
while (stream.CanRead)
{
double readGPA = reader.ReadDouble();
if (readGPA > lowerGPA && readGPA < upperGPA)
{
UInt32 readStudentID = reader.ReadUInt32();
String readStudentName = reader.ReadString();
String readStudentSurname = reader.ReadString();
String readStudentEmail = reader.ReadString();
Byte readStudentYear = reader.ReadByte();
sideObj.appendToFile(GPAFilterFileName, readStudentID, readStudentName, readStudentSurname, readStudentEmail, readStudentYear, readGPA);
}
}
reader.Close();
reader.Dispose();
stream.Close();
stream.Dispose();
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + "\n" + ex.Source);
return false;
}
}
我最初用来附加数据的函数。
public bool appendToFile (string fileName, UInt32 studentID, string name, string surname, string email, byte classYear, double gpa){
if (!File.Exists (fileName)) {
bool success = createBinaryFile (fileName);
if (!success) {
return false;
}
}
try{
BinaryWriter writer = new BinaryWriter (File.Open (fileName, FileMode.Append));
writer.Write (studentID);
writer.Write (name);
writer.Write (surname);
writer.Write (email);
writer.Write (classYear);
writer.Write (gpa);
writer.Close ();
writer.Dispose ();
return true;
}
catch{
return false;
}
}
【问题讨论】:
-
BinaryReader.ReadDouble不读取一行,它从流中读取 8 个字节并将它们解释为双精度浮点值 - 听起来你有一个 text文件,并且您应该使用描述中的StreamReader。 -
感谢您的建议,使用 BinaryWriter 将数据写入 .dat 文件。这就是我必须首先使用 BinaryReader 的原因。我正在使用用于将数据附加到 .dat 文件的函数来编辑问题。
-
阅读文档。
CanRead没有做你认为它做的事情:) -
哦,我明白了。谢谢@luaan。我尝试检查
while(reader.PeekChar() != -1),但它会引发The output char buffer is too small to contain the decoded characters, encoding 'Unicode (UTF-8)' fallback错误。你会建议比较长度和位置吗? -
是的,
stream.Position != stream.Length解决了它
标签: c# loops while-loop binary