why define size_t ssize_t ?

why define size_t ssize_t ?

http://blog.csdn.net/yuwenliang/archive/2010/01/18/5207491.aspx

 

 

ssize_t说明

Data Type: ssize_t
This data type is used to represent the sizes of blocks that can be read or written in a single operation. It is similar to size_t , but must be a signed type.

 

Function: ssize_t read (int filedes , void *buffer , size_t size )
The read function reads up to size bytes from the file with descriptor filedes , storing the results in the buffer . (This is not necessarily a character string, and no terminating null character is added.)

The return value is the number of bytes actually read. This might be less than size ; for example, if there aren't that many bytes left in the file or if there aren't that many bytes immediately available. The exact behavior depends on what kind of file it is. Note that reading less than size bytes is not an error.

A value of zero indicates end-of-file (except if the value of the size argument is also zero). This is not considered an error. If you keep calling read while at end-of-file, it will keep returning zero and doing nothing else.

If read returns at least one character, there is no way you can tell whether end-of-file was reached. But if you did reach the end, the next read will return zero.

In case of an error, read returns -1 .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于上述代码的优化,可以考虑以下几点: 1. 使用头文件保护宏(Header Guard):可以避免头文件被重复包含,可以改进为如下形式: ```c #ifndef SERIAL_H #define SERIAL_H // 原有的代码内容 #endif // SERIAL_H ``` 2. 使用预处理器常量替代魔法数值:将一些魔法数值(例如设备路径、波特率)定义为预处理器常量,增加代码的可读性和可维护性。 3. 添加错误处理:在函数中添加错误处理机制,例如返回值表示操作是否成功,以及错误码表示具体错误原因。 4. 添加参数校验:对输入参数进行合法性校验,避免潜在的错误操作。 根据以上优化建议,可以改进的代码如下: ```c #ifndef SERIAL_H #define SERIAL_H #include <stddef.h> // 错误码定义 #define SERIAL_SUCCESS 0 #define SERIAL_ERROR -1 // 设备路径最大长度 #define SERIAL_MAX_PATH_LEN 256 // 初始化串口 int serial_init(const char *devpath, int baudrate); // 接收数据 ssize_t serial_recv(int fd, void *buf, size_t count); // 发送数据 ssize_t serial_send(int fd, const void *buf, size_t count); // 精确接收指定字节数 ssize_t serial_recv_exact_nbytes(int fd, void *buf, size_t count); // 精确发送指定字节数 ssize_t serial_send_exact_nbytes(int fd, const void *buf, size_t count); // 退出串口 int serial_exit(int fd); #endif // SERIAL_H ``` 请注意,这只是对代码的简单优化建议,具体的优化方式还需要根据项目需求和实际情况进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值