linux C++ 读取文件到buf

#include <iostream>
#include <fstream>

    std::filebuf *pbuf;
    std::ifstream filestr;
    long size;
    char * buffer;
    // 要读入整个文件,必须采用二进制打开
    filestr.open ("../scripts/lua_script_test.lua", std::ios::binary);
    // 获取filestr对应buffer对象的指针
    pbuf=filestr.rdbuf();

    // 调用buffer对象方法获取文件大小
    size=pbuf->pubseekoff (0,std::ios::end,std::ios::in);

    pbuf->pubseekpos (0,std::ios::in);
    // 分配内存空间
    buffer = new char[size];

    // 获取文件内容
    pbuf->sgetn (buffer,size);

    filestr.close();
    // 输出到标准输出
    std::cout.write (buffer,size);

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Linux下,可以使用C++中的文件操作和多线程技术实现高并发读写串口。具体实现步骤如下: 1. 打开串口设备文件 使用C++中的文件操作函数`open()`打开串口设备文件,获取文件描述符。例如: ```c++ int fd = open("/dev/ttyS0", O_RDWR|O_NOCTTY|O_NDELAY); if (fd < 0) { perror("open serial port error!"); return -1; } ``` 其中,`/dev/ttyS0`是串口设备文件路径,`O_RDWR`表示打开文件可读可写,`O_NOCTTY`表示不把串口设备作为控制终端,`O_NDELAY`表示非阻塞模式打开。如果打开失败,使用`perror()`函数输出错误信息并返回。 2. 配置串口属性 使用Linux系统调用函数`tty_ioctl()`配置串口属性,包括波特率、数据位、停止位和校验位等。例如: ```c++ struct termios options; tcgetattr(fd, &options); cfsetispeed(&options, B9600); cfsetospeed(&options, B9600); options.c_cflag |= (CLOCAL | CREAD); options.c_cflag &= ~CSIZE; options.c_cflag |= CS8; options.c_cflag &= ~PARENB; options.c_cflag &= ~CSTOPB; options.c_cc[VTIME] = 0; options.c_cc[VMIN] = 1; tcsetattr(fd, TCSANOW, &options); ``` 其中,`cfsetispeed()`和`cfsetospeed()`函数设置输入输出波特率,`c_cflag`成员设置串口属性,`VTIME`和`VMIN`成员配置读取等待时间和最小字符数。如果配置失败,使用`perror()`函数输出错误信息并返回。 3. 创建读写线程 使用C++中的多线程技术创建读写线程,分别实现串口数据的读取和写入。例如: ```c++ void* read_thread(void* arg) { int fd = *(int*)arg; char buf[1024]; while (1) { int n = read(fd, buf, sizeof(buf)-1); if (n > 0) { buf[n] = '\0'; printf("read data: %s\n", buf); } usleep(10000); } return NULL; } void* write_thread(void* arg) { int fd = *(int*)arg; char buf[1024]; while (1) { fgets(buf, sizeof(buf), stdin); int n = write(fd, buf, strlen(buf)); if (n < 0) { perror("write serial port error!"); break; } } return NULL; } int main() { int fd = open("/dev/ttyS0", O_RDWR|O_NOCTTY|O_NDELAY); if (fd < 0) { perror("open serial port error!"); return -1; } pthread_t tid1, tid2; pthread_create(&tid1, NULL, read_thread, &fd); pthread_create(&tid2, NULL, write_thread, &fd); pthread_join(tid1, NULL); pthread_join(tid2, NULL); close(fd); return 0; } ``` 其中,`read_thread()`函数实现串口数据的读取,`write_thread()`函数实现串口数据的写入。使用`pthread_create()`函数创建两个线程,并传递串口文件描述符作为参数。主线程使用`pthread_join()`函数等待两个线程退出。如果读写失败,使用`perror()`函数输出错误信息并退出。 以上就是Linux C++高并发读写串口的实现方法。需要注意的是,在多线程环境下,需要加锁保证数据的同步和互斥访问。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值