在我使用“使用System;”,“using System.IO”和“namespace BinaryFileApplication”的行上。所以我真的不知道如何处理它们让C程序认出它们。
using System;
using System.IO;
namespace BinaryFileApplication
{
class Program
{
static void Main(string[] args)
{
BinaryWriter bw;
BinaryReader br;
int i = 25;
double d = 3.14157;
bool b = true;
string s = "I am happy";
//create the file
try
{
bw = new BinaryWriter(new FileStream("mydata", FileMode.Create));
}
catch (IOException e)
{
Console.WriteLine(e.Message + "\n Cannot create file.");
return;
}
//writing into the file
try
{
bw.Write(i);
bw.Write(d);
bw.Write(b);
bw.Write(s);
}
catch (IOException e)
{
Console.WriteLine(e.Message + "\n Cannot write to file.");
return;
}
bw.Close();
//reading from the file
try
{
br = new BinaryReader(new FileStream("mydata", FileMode.Open));
}
catch (IOException e)
{
Console.WriteLine(e.Message + "\n Cannot open file.");
return;
}
try
{
i = br.ReadInt32();
Console.WriteLine("Integer data: {0}", i);
d = br.ReadDouble();
Console.WriteLine("Double data: {0}", d);
b = br.ReadBoolean();
Console.WriteLine("Boolean data: {0}", b);
s = br.ReadString();
Console.WriteLine("String data: {0}", s);
}
catch (IOException e)
{
Console.WriteLine(e.Message + "\n Cannot read from file.");
return;
}
br.Close();
Console.ReadKey();
}
}
答案 0 :(得分:1)
你不能。这看起来像.Net代码。为什么会期待一个" C"编译器了解它?
答案 1 :(得分:0)
此代码不是C - 它的C#。您必须使用 C#编译器(在Visual Studio中,或使用Mono,或类似的东西)构建它。
如果确实想要将其构建为,则必须将其转换为合法的C代码。最接近的等价物如下:
#include <stdio.h>
int main( int argc, char **argv )
{
FILE *bw, *br;
int i = 25;
double d = 3.14157;
_Bool b = true;
char s[] = "I am happy";
bw = fopen( "mydata", "wb" );
if ( bw )
{
if ( fwrite( &i, sizeof i, 1, bw ) != sizeof i )
// error writing i;
if ( fwrite( &d, sizeof d, 1, bw ) != sizeof d )
// error writing d
if ( fwrite( &b, sizeof b, 1, bw ) != sizeof b )
// error writing b
if ( fwrite( s, sizeof s, 1, bw ) != sizeof s ) // no & operator on s
// error writing s
fclose( bw );
}
// remainder left as exercise
}
C没有名称空间 1 ,它没有类,它没有BinaryReader
或BinaryWriter
,它没有& #39;进行结构化异常处理等。它与C#完全不同的语言。
<小时/>