将标头与缓冲区内容连接在一起

时间:2013-12-06 14:43:53

标签: c

我正在逐块读取文件并通过TCP连接发送。对于每个块,我必须在发送消息之前添加一个短标题。对于我的生活,我无法让这个工作:

do {
    bytes_read = fread( &buffer, sizeof(char), BUFFSIZE-sizeof("your_file||")-1, fp );
    bzero(message, BUFFSIZE);
    strcpy(message, "your_file|");

    for (j=0; j<bytes_read; ++j) {
        fprintf(stdout, "%c", buffer[j]);
        message[j+9] = buffer[j];
    }

    strcat(message, "|");
    strcat(message, "\0");
    fprintf(stdout, "message:    %s\n\n", message);
} while (!feof(fp1));

我的printf输出显示了完美的数据,所以我知道我正在阅读。但我无法得到这个消息。这就是我的输出:

BEGIN_LINE000This is a test file with exactly 10 lines of readable textEND_LINE000
message:    your_file|

BEGIN_LINE001This is a test file with exactly 10 lines of readable textEND_LINE001
BEGIN_LINE002This is a test file with exactly 10 lines of readable textEND_LINE002
BEGIN_LINE003This is a test file with exactly 10 lines of readable textEND_LINE003
BEGIN_LINE004This is a test file with exactly 10 lines of readable textEND_LINE004
BEGIN_LINE005This is a test file with exactly 10 lines of readable textEND_LINE005
BEGIN_LINE006This is a test file with exactly 10 lines of readable textEND_LINE006
BEGIN_LINE007This is a test file with exactly 10 lines of readable textEND_LINE007
BEGIN_LINE008This is a test file with exactly 10 lines of readable textEND_LINE008
BEGIN_LINE009This is a test file with exactly 10 lines of readable textEND_LImessage:    your_file|

NE009
BEGIN_LINE010This is a test file with exactly 10 lines of readable textEND_LINE010message:    your_fileNE009
BEGIN_LINE010This is a test file with exactly 10 lines of readable textEND_LINE010|

我确信我忽略了一些非常简单的事情,但我花了好几个小时尝试不同的方法来解决这个问题,而且我总是回到同样的问题。谁能告诉我我做错了什么?感谢。

1 个答案:

答案 0 :(得分:0)

除非您知道for的最后一个字符始终为{{},否则无法保证message循环最终会在buffer中留下正确终止的字符串。 1}}。

如果终止失败,则在'\0'上调用strcat()并且(当然)将其打印为字符串会很危险。