我正在尝试将输入字符串从管道转换为十六进制,输入为8KB,但转换后的十六进制仅为6KB,我打印出普通输入,并且正确的行来了。我也尝试将十六进制字符串写到共享内存中,也许我的问题是内存指针,但我不确定。
但是,对于少量输入,它可以正确打印出十六进制,我被卡住了。
字符串为十六进制:
void stringtohex(char* input, char* output)
{
int loop;
int i;
i=0;
loop=0;
while(input[loop] != '\0')
{
sprintf((char*)(output+i),"%02X", input[loop]);
loop+=1;
i+=2;
}
//insert NULL at the end of the output string
output[i++] = '\0';
}
阅读部分:
int num;
char s[BUFFER_SIZE];
while((num = read(fd, s, BUFFER_SIZE)) > 0)
{
//fprintf(stderr, "input: \n%s\n", s);
int len = strlen(s);
char hex[(len*2) + 1];
stringtohex(s, hex);
sprintf(ptr_child_2, "%s", hex);
ptr_child_2 += strlen(hex);
}
此处ptr是映射到共享内存的void *。
使用read
将数据读入s
,然后将s
视为字符串是错误的。函数read
不了解字符串。它只是尝试读取BUFFER_SIZE
字节。因此,您可能会得到少于一个字符串或多个字符串,但不太可能仅获得一个字符串(如您的代码所假定的那样)。
改为查看fgets
。
BTW:检查sprintf
返回的内容...您会发现它有用;-)