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

C 将标头与缓冲区内容连接在一起,c,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_

我正在逐块读取文件并通过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));

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

除非您知道
缓冲区的最后一个字符始终是
“\0”
,否则不能保证
for
循环在
消息中留下正确终止的字符串


如果未能终止,则在
消息
上调用
strcat()
,以及(当然)将其打印为字符串,都会造成危险。

我确信它没有正确终止。如何将nul终结者放在它的末尾?我尝试了
message[j]='\0'
,但这只会给我一个分段错误。应该说
message[j+9]='\0'
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|