【发布时间】:2015-07-22 08:41:38
【问题描述】:
基本上我有一个连接到树莓派的 com 端口,我正在尝试将接收到的数据附加到 .txt 文件中。到目前为止,我只成功打开了文件。我应该如何编辑现有代码以使其能够将数据“保存”到打开的文件中?
我也尝试过编辑它:
FILE *f;
f = fopen("try.txt", "a");
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
int r;
char buf[255];
while( 1 )
{
r = read( fd, buf, 255 );
buf[r]=0;
fprintf( f, "%s", buf);
}
fclose(f);
但似乎这会阻止接收数据。
现在已有的代码如下:
#include <fcntl.h>
#include <stdio.h>
#include <termios.h>
#include <stdlib.h>
#include <strings.h>
#define SPEED B9600
#define PORT "/dev/ttyUSB0"
int main( )
{
int fd = open( PORT, O_RDONLY | O_NOCTTY );
if (fd <0)
{
perror(PORT);
exit(-1);
}
struct termios options;
bzero(&options, sizeof(options));
options.c_cflag = SPEED | CS8 | CLOCAL | CREAD | IGNPAR;
tcflush(fd, TCIFLUSH);
tcsetattr(fd, TCSANOW, &options);
FILE *f;
f = fopen("try.txt", "a");
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
int r;
char buf[255];
while( 1 )
{
r = read( fd, buf, 255 );
buf[r]=0;
printf( "%s", buf);
}
}
新的 raspbian 等。任何帮助将不胜感激。
【问题讨论】:
-
请格式化您的代码。
-
@MichaelWalz 对不起...格式...?是什么意思?
-
格式或标识意味着在每行的开头放置空格以表示程序的块,使其更具可读性。看看你的程序,看看你的C教科书中的例子,你会发现不同
-
您的输入是面向行的文本,还是可以包含二进制数据?您打算如何跳出
while(1)循环(中断可能会丢失数据)?
标签: c raspberry-pi port raspbian