【请教】linux 读串口的数据写到.txt 文件,第二行多出来个^@ 什么原因?

amao805 2018-02-07 01:46:09
最近在学习linux 串口操作,计划是把从串口读到的数据 写到一个 .TXT 文件,发现下写完定义的char title[] = "time data\n"; 字符后,第二行总会多出来一下^@ 内容,这个对应的是\0 字符,可代码里面没有写过这个字符,不知道这个字符是怎么出来的,请教各位是否有遇到过的,指点一下,谢谢! 如下是代码和测试的结果。



//串口配置函数
int serial_test(void)
{

char testdata[]={0xfe,0x19,0x26,0x34};
char dataread[10];
bzero(dataread,sizeof(dataread));
fd0 = open("/dev/ttyS2",O_RDWR);

if(fd0 <0)
{
printf("open serial fail\n");
return 1;
}
tcgetattr(fd0, &oldtio); /* Save fd1 setting */
tcgetattr(fd0, &newtio);
newtio.c_cflag = B115200 | CS8 | CREAD | CLOCAL;
newtio.c_iflag = IGNPAR;
newtio.c_oflag = 0;
newtio.c_lflag = 0;
newtio.c_cc[VMIN] = 1;
newtio.c_cc[VTIME] = 0;
tcflush(fd0, TCIFLUSH);
tcsetattr(fd0, TCSANOW, &newtio); /* Configuration fd1 *///使设置的终端属性立即生效
printf("serial ok\n");
sleep(1);

}
/// 串口线程函数
void *serial_read_data(void * arg)
{
fd_set fdR;
//char buff[30] = {0};
int fd1;
struct timeval timeout= {0,0};
int rselect;
time_t timer;
char timebuff[40];
char buff[256];
int len,len1,len2;
char kongge[] = " ";
char title[] = "time data\n";
char huanghang[] = "\n";
char rdatabuff[100] = {0};


fd0 = open("/dev/ttyS2",O_RDWR);
tcflush(fd0,TCIFLUSH);
sleep(4);

fd1 = open("/umsd/stest.txt",O_RDWR|O_CREAT|O_TRUNC);
lseek(fd1,0,SEEK_END);
write(fd1,title,sizeof(title));
timeout.tv_sec = 10;
bzero(buff,sizeof(buff));
bzero(timebuff,sizeof(timebuff));

if(fd0< 0)
{
printf("open fuji serial fild\n");
}
while (1)
{
FD_ZERO(&fdR);
FD_SET(fd0,&fdR );
rselect = select(fd0+1,&fdR,NULL,NULL,&timeout);
switch (rselect)
{
case -1:
printf("serial error\n");
break;
case 0:
// printf("serial no read data\n");
break;
default:
if(FD_ISSET(fd0,&fdR))
{
len1 = read(fd0,rdatabuff,sizeof(rdatabuff));
timer = time(NULL);
ctime_r(&timer,timebuff);
len= strlen(timebuff);
strncpy(buff,timebuff,len-1);
strcat(buff,kongge);
strcat(buff,rdatabuff);
strcat(buff,huanghang);
len2 = strlen(buff);
write(fd1,buff,len2);
printf("read data ok %s\n",buff);
bzero(buff,sizeof(buff));
bzero(rdatabuff,sizeof(rdatabuff));
}
}
}
/// 测试结果
/mnt/home # cd /umsd
/umsd # vi stest.txt
time data
^@Wed Feb 7 09:09:50 2018 123456789
Wed Feb 7 09:10:00 2018 serial ok
Wed Feb 7 09:10:02 2018 123456789
...全文
678 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
weixin_40388280 2020-12-30
  • 打赏
  • 举报
回复
你好,这个问题您解决了吗?
宁南学者 2018-02-07
  • 打赏
  • 举报
回复
既有可能是不可见的\r\n 等字符,可以从16进制工具od 命令查看下。

427

社区成员

发帖
与我相关
我的任务
社区描述
非技术问题的乐园
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧