linux文件编程-read

read() 函数是用于从文件描述符中读取数据的系统调用函数。其函数原型如下

#include <unistd.h>

ssize_t read(int fd, void *buffer, size_t count);
  • fd:要读取数据的文件描述符。
  • buffer:存储读取数据的缓冲区。
  • count:要读取的最大字节数。

read() 函数的返回值是实际读取的字节数,如果出现错误,返回值会有特定的负数。

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

int main(void)
{
    int fd;
    char *buf = "jieda handsome !";

    // 打开文件 file1,以读写模式打开
    fd = open("./file1", O_RDWR);
    if (fd == -1)
        printf("fd=%d open file1 fail\n", fd);

    // 打开文件 file1,如果文件不存在则创建它,并设置权限为 0600 (只允许拥有者读写)
    fd = open("./file1", O_RDWR | O_CREAT, 0600);
    printf("fd=%d open file1 SUCCESS\n", fd);

    // 写入数据到文件
    int write_size = write(fd, buf, strlen(buf));
    printf("write %d\n", write_size);

    // 读取文件中的数据
    char *readbuf;
    readbuf = (char *)malloc(sizeof(char) * write_size);
    int read_size = read(fd, readbuf, write_size);
    printf("read %d readbuf:%s\n", read_size, readbuf);
    
    // 关闭文件
    close(fd);
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
RS485-RTU通讯是一种广泛应用于工业自动化领域的通讯协议,Linux下可以使用各种编程语言实现RS485-RTU通讯。 下面以C语言为例,介绍如何在Linux下实现RS485-RTU通讯编程。 1. 打开串口设备 使用Linux下的串口设备文件(如/dev/ttyS0或/dev/ttyUSB0等),可以使用open函数打开串口设备,例如: ```c int fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY); if (fd < 0) { perror("Open serial port failed"); return -1; } ``` 其中,O_RDWR表示以读写方式打开串口设备,O_NOCTTY表示不将串口设备作为控制终端,O_NDELAY表示非阻塞方式打开串口设备。 2. 配置串口参数 在打开串口设备后,需要配置串口的波特率、数据位、停止位、校验位等参数,可以使用tcgetattr和tcsetattr函数实现,例如: ```c struct termios options; tcgetattr(fd, &options); cfsetispeed(&options, B9600); // 设置波特率为9600 cfsetospeed(&options, B9600); options.c_cflag |= CLOCAL; // 忽略调制解调器线路状态 options.c_cflag |= CREAD; // 开启接收器 options.c_cflag &= ~CSIZE; // 清除数据位设置 options.c_cflag |= CS8; // 设置数据位为8位 options.c_cflag &= ~PARENB; // 禁用校验位 options.c_cflag &= ~CSTOPB; // 设置停止位为1位 tcsetattr(fd, TCSANOW, &options); ``` 3. 发送数据 在配置好串口参数后,可以使用write函数向串口设备发送数据,例如: ```c char data[] = {0x01, 0x03, 0x00, 0x00, 0x00, 0x01, 0x84, 0x0A}; int len = write(fd, data, sizeof(data)); if (len != sizeof(data)) { perror("Write data failed"); return -1; } ``` 其中,data为待发送的数据,sizeof(data)为数据长度。 4. 接收数据 在发送数据后,可以使用read函数从串口设备接收数据,例如: ```c char buffer[256]; int len = read(fd, buffer, sizeof(buffer)); if (len > 0) { // 处理接收到的数据 } else { perror("Read data failed"); return -1; } ``` 其中,buffer为接收数据的缓冲区,sizeof(buffer)为缓冲区长度。 5. 关闭串口设备 在使用完串口设备后,需要使用close函数关闭串口设备,例如: ```c close(fd); ``` 以上就是在Linux下实现RS485-RTU通讯编程的基本步骤,具体实现还需要根据具体应用场景进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MichstaBe#

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值