文件是什么?
计算机中的文件是存储在外部介质(通常是磁盘)上的数据集合,文件分为文本文件和二进制文件。
os.Open() 函数能够打开一个文件,返回一个 *File 和一个 err 。对得到的文件实例调用 close() 方法能够关闭文件。
为了防止文件忘记关闭,我们通常使用defer注册文件关闭语句。
Read方法定义如下:
它接收一个字节切片,返回读取的字节数和可能的具体错误,读到文件末尾时会返回 0 和 io.EOF 。 举个例子:
使用for循环读取文件中的所有数据。
bufio是在file的基础上封装了一层API,支持更多的功能。
io/ioutil 包的 ReadFile 方法能够读取完整的文件,只需要将文件名作为参数传入。
os.OpenFile() 函数能够以指定模式打开文件,从而实现文件写入相关功能。
其中:
name :要打开的文件名 flag :打开文件的模式。 模式有以下几种:
perm :文件权限,一个八进制数。r(读)04,w(写)02,x(执行)01。
1 select语句的每个case语句必须IO操作2 执行 case 语句顺序是随机的
3 select的每个case(包含default)语句是阻塞的
4 如果case语句均发生阻塞,那么执行default语句
//创建一个串口通讯SerialPort CurrentPort = null
CurrentPort = new SerialPort()
CurrentPort.ReadBufferSize = 128
CurrentPort.PortName = comName //端口号
CurrentPort.BaudRate = bandRate//比特率
CurrentPort.Parity =parity//奇偶校验
CurrentPort.StopBits = stop//停止位
CurrentPort.DataBits = databit//数据位
CurrentPort.ReadTimeout = 1000//读超时,即在1000内未读到数据就引起超时异常
//绑定数据接收事件,因为发送是被动的,所以你无法主动去获取别人发送的代码,只能通过这个事件来处理
CurrentPort.DataReceived += Sp_DataReceived
CurrentPort.Open()
定义一个变量 byte[] receiveStr
//绑定的事件处理函数
private static void Sp_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
SerialPort sp = sender as SerialPort
if (sp == null)
return
byte[] readBuffer = new byte[sp.ReadBufferSize]
sp.Read(readBuffer, 0, readBuffer.Length)
//赋值
receiveStr=readBuffer//当然你可以通过转换将byte[]转换为字符串。
}
//你要求的按钮事件可以这么写
private void button1_Click(object sender, EventArgs e)
{
if(receiveStr!=null)
{
变量 xxx=receiveStr
}
}