C语言open()打开文件
函数:open() --><io.h>(头文件)
函数原型:int open(char *path,int access[,int auth]);
函数解析:
char *path —文件路径
int access —打开方式
返回值:成功 返回文件句柄(大于0,不同于access) ,失败 返回-1
#include<stdio.h>
#include<fcntl.h>
int main(void){
/*以读写或者创建方式打开串口*/
int fd = open("/dev/ttyS0", O_RDWR);
if(fd < 0){
/* 不能打开串口*/
printf("can not open the port\n");
return fd;
}
printf("fd:-------%d------\n",fd);
printf("successful to open the port\n");
return 0;
}
C语言read()读取文件
函数:read()–><io.h>(头文件)
函数原型: int read(int handle,void *buf,int len);
函数解析:
int handle 为要读取的文件
void *buf 为要将读取的内容保存的缓冲区
int len 读取文件的长度
返回值:返回实际读取的字节数
程序例:创建文件,内容为 I like potato!
//打开文件,读取文件的内容
#include<stdio.h>
#include<io.h>
#include<fcntl.h>
int main(void){
int fd=open("D:\\a.txt",O_RDONLY);
if(fd==-1){
printf("can not open the file\n");
return 1;
}
char buf[1024]={"\0"};
int len=read(fd,buf,1024);
printf("%s\nlen=%d\n",buf,len);
close(fd);
return 0;
}
运行结果:
I like potato!
len:14
LINUX控制终端tcgetattr和tcsetattr
函数 | 功能 | 函数形式 | 返回值 |
---|---|---|---|
tcgetattr | 获取终端参数 | int tcgetattr(int fd, struct termios *termios_p) | 成功0 失败-1 |
tcsetattr | 设置终端参数 | int tcsetattr(int fd, int optional_actions, const struct termios *termios_p) | 成功0 失败-1 |
fd为终端的文件描述符,也就是上面打开文件 | |||
tcgetattr:返回的结果保存在termios结构体中 |
LINUX波特率设置函数cfsetospeed和cfsetispeed,波特率获取函数cfgetispeed和cfgetospeed
函数 | 功能 | 函数形式 | 返回值 |
---|---|---|---|
cfsetospeed | 设置输出波特率 | int cfsetospeed(struct termios *termptr, speed_t speed) | 成功0 失败-1 |
cfsetispeed | 设置输入波特率 | int cfsetispeed(struct termios *termptr, speed_t speed) | 成功0 失败-1 |
cfgetospeed | 获取输出波特率 | speed_t cfgetospeed(const struct termios *termptr) | 成功0 失败-1 |
cfgetispeed | 获取输入波特率 | speed_t cfgetispeed(const struct termios *termptr) | 成功0 失败-1 |
串口编程 函数tcflush
函数 | 功能 | 函数形式 | 返回值 |
---|---|---|---|
tcflush | 刷清输入或输出缓存 | int tcflush(int fd, int queue_selector) | 成功0 失败-1 |
queue_selector参数: | |||
TCIFLUSH // 清除正收到的数据,且不会读取出来。 | |||
TCOFLUSH // 清除正写入的数据,且不会发送至终端。 | |||
TCIOFLUSH // 清除所有正在发生的I/O数据。 |