在String中注入的二进制数据

时间:2011-06-14 04:21:08

标签: c++ string named-pipes

我有一块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打印的文本块很好,但在null终止char数组后,我最终在“command”字符串中使用二进制垃圾:

Command0:

Command1:

Command2:

除此之外,一切似乎都很好。 char []正确地连接到命令字符串,所以我最终得到了完整的字符串,前端只有一些额外的二进制文件。我有一个奇怪的数组出界问题,这是写入命令的内存吗?

2 个答案:

答案 0 :(得分:3)

在以下情况下,

if ((num = read(fd, s, 255))

如果num = 255;

s[num+1] = '\0';

会将s[256] = 0;设置为超出s[0] to s[255]的范围。

答案 1 :(得分:1)

而不是:

    command += s;

你试过了吗?

command.append(s, num);

这样你就不需要打扰空终止等了,只需添加读取字符。