我想使用一个函数,该函数负责通过使用将“数据大小”和“数据”发送到特定文件描述符write()
。它在记录长度等于 2 个字节时起作用。但是,我想使用相同的函数发送也等于 1 字节的记录长度。
send_func(int port)
{
void *fd;
uint64_t fsize = 2517283;
uint64_t nbrBytes = 0;
uint16_t rsize;
int count;
ssize_t ret;
uint8_t Bsent = 0;
for (count = 1; nbrBytes < fsize; count++)
{
rsize = ((uint8_t*)fp)[nbrBytes];
rsize += ((((uint8_t*)fp)[nbrBytes + 1]) << 8) & 0xFF00;
nbrBytes += 2;
// send size
ret = write(port, rsize, 2);
if (ret != 2) {
return -1;
}
// send data
ret = write(port, ((unsigned char*)fp) + Bsent, rsize - Bsent);
if (ret < 0) {
return -1;
}
Bsent += ret;
}
}
send_func(int port)
{
void *fd;
uint64_t fsize = 2517283;
uint64_t nbrBytes = 0;
size_t rsize;
int count;
ssize_t ret;
uint8_t Bsent = 0;
for (count = 1; nbrBytes < fsize; count++)
{
if (mode == ONLY_1_BYTE) {
rsize = ((uint8_t*)fp)[nbrBytes];
rsize += ((((uint8_t*)fp)[nbrBytes + 1]));
nbrBytes += 1;
do {
// send data
ret = write(port, ((unsigned char*)fp) + Bsent, rsize - Bsent);
if (ret < 0) {
return -1;
}
Bsent += ret;
} while(Bsent < rsize)
}
else
{
rsize = ((uint8_t*)fp)[nbrBytes];
rsize += ((((uint8_t*)fp)[nbrBytes + 1]) << 8) & 0xFF00;
nbrBytes += 2;
// send size
ret = write(port, rsize, sizeof(uint16_t));
if (ret != 2) {
return -1;
}
}
do {
// send data
ret = write(port, ((unsigned char*)fp) + Bsent, rsize - Bsent);
if (ret < 0) {
return -1;
}
Bsent += ret;
} while(Bsent < rsize)
}
}
因为第二种情况只有 1 个长度字节,所以我自愿去掉了字节序操作,这是 2 个字节的情况下必须的。
这是最好的练习方式吗?