C在while循环中连接字符串

时间:2016-09-13 06:45:28

标签: c string concatenation strcat

我似乎无法使用以下函数来连接while循环中的字符串。知道我做错了吗?

void do_file(FILE *in, FILE *out, OPTIONS *options)
{
    char ch;
    int loop = 0;
    int sz1,sz2,sz3;

    int seeker = offsetof(struct myStruct, contents.datas);

    //find total length of file
    fseek(in, 0L, SEEK_END);
    sz1 = ftell(in);

    //find length to struct beginning and minus that from total length
    fseek(in, seeker, SEEK_SET);
    sz2 = sz1 - ftell(in);

    sz3 = (sz2 + 1) * 2;//Allocate enough size for 2x array length
    char buffer[sz3];//set size of buffer to be copied to
    char msg[sz3];//set size of msg

    buffer[0] = '\0';

    while (loop < sz2)
    {
        if (loop == sz2)
        {
            break;
        }

        fread(&ch, 1, 1, in);
        //sprintf(msg, "%02X", (ch & 0x00FF));
        strcat(buffer, msg);

        ++loop;
    }
    printf("%s\n", buffer);
}

1 个答案:

答案 0 :(得分:0)

您唯一的strcat会附加永不填充的char msg[sz3];

修改 最简单的解决方法是添加

msg[1] = '\0';

char msg[sz3];//set size of msg

并替换

fread(&ch, 1, 1, in);

fread(&msg[0], 1, 1, in);