我有一块C++代码从命名管道读取文本。相关部分是:在字符串中注入二进制数据
char s[256];
int num, fd;
string command;
command.erase(); //Clear the command string
cout << "Command0:" << endl << command << endl;
fd = open(FIFO_NAME, O_RDONLY); //Will block until a writer connects
do {
if ((num = read(fd, s, 255)) == -1)
perror("read");
else {
cout << "Command1:" << endl << command << endl;
s[num+1] = '\0';
cout << "Command2:" << endl << command << endl;
//printf("read %d bytes: \"%s\"\n", num, s);
command += s;
}
} while (num > 0);
cout << "Command:" << endl << command << endl;
“commandX”printfs是一些调试代码,我将在一秒钟内引用输出。文本块是那些获得读入S打印就好了,但空终止字符数组后,我在“命令”的字符串结束与二进制垃圾:
Command0:
Command1:
Command2:
除此之外,一切都显得工作正常。 char []正确连接到命令字符串上,所以我最终得到了完整的字符串,只是在前端添加了一些额外的二进制文件。我是否有一个奇怪的数组越界问题,这是写入命令的内存?
我认为空终止应该在索引'num'而不是'num + 1'处。如果你已经读过'num'字符,那么它们从'0'填充到'num-1'索引。 – Mahesh 2011-06-14 04:28:12
它应该是s [num] ='\ 0'而不是num + 1。 – Duck 2011-06-14 04:28:21