我需要从串口读取数据,但read()函数总是返回8个字节或更少,我该如何获取所有数据 c代码:
readbytes = read(f, bufptr, sizeof(buffer));
buffer[readbytes]='\0';
printf("number of bytes read is %d\n", readbytes);
printf("buffer %s\n", buffer);
我尝试使用do while,但我仍然有相同的结果。
答案 0 :(得分:1)
[评论太久了]
试试这段代码:
char buffer[256];
memset(buffer, 0, 256);
size_t bytes_read= 0, bytes_expected = 11;
do {
ssize_t result = read(f, buffer + bytes_read, bytes_expected - bytes_read);
if (0 >= result)
{
if (0 > result)
{
perror("read()");
}
break;
}
bytes_read+= result;
} while (bytes_read < bytes_expected)
fprintf(stderr, "Read %zu out of %zu expected bytes: `%s`\n", bytes_read, bytes_expected, buffer);