如何:读取二进制文件
更新:2007 年 11 月
下面的代码示例演示如何从文件中读取二进制数据。使用了 System.IO 命名空间中的两个类:FileStream 和 BinaryReader。FileStream 表示实际的文件。BinaryReader 为允许二进制访问的流提供接口。
下面的代码示例使用由 如何:编写二进制文件 中的代码创建的称为 data.bin 的文件。
示例
// binary_read.cpp
// compile with: /clr
#using<system.dll>
using namespace System;
using namespace System::IO;
int main()
{
String^ fileName = "data.bin";
try
{
FileStream^ fs = gcnew FileStream(fileName, FileMode::Open);
BinaryReader^ br = gcnew BinaryReader(fs);
Console::WriteLine("contents of {0}:", fileName);
while (br->BaseStream->Position < br->BaseStream->Length)
Console::WriteLine(br->ReadInt32().ToString());
fs->Close( );
}
catch (Exception^ e)
{
if (dynamic_cast<FileNotFoundException^>(e))
Console::WriteLine("File '{0}' not found", fileName);
else
Console::WriteLine("Exception: ({0})", e);
return -1;
}
return 0;
}