c - strcat 给出意外结果

标签 c file pointers binaryfiles hexdump

这是一个大型项目的一小部分......

这些是在项目的标准头文件中定义的 typedef。

typedef uint16_t u_int16_t;
typedef uint32_t u_int32_t;
typedef uint8_t  u_int8_t;

现在这是导致问题的实际函数......

void function(u_int8_t *data1, u_int32_t data1len,
    u_int8_t *data2, u_int32_t data2len)
{

FILE *fq,*fr,*fs;
    char *data3;
    int data3len;

    data3len=data1len+data2len;

    printf("\n%d",data1len);
    printf("\n%d",data2len);
    printf("\n%d",data3len);

fq=fopen("data1.txt","wb");
fwrite((char *)data1,data1len,1,fq);

fr=fopen("data2.txt","wb");
fwrite((char *)data2,data2len,1,fr);

data3=(char *)data1;
strcat(data3,(char *)data2);

fs=fopen("data3.txt","wb");
fwrite((char *)data3,data3len,1,fs);

}

一些输出快照...

40
14
54


 udit@udit-Dabba ~$ hexdump -C data1.txt
 00000000  60 00 00 00 00 8c 06 00  00 00 00 00 00 00 00 00  |`...............|
 00000010  00 00 00 00 00 00 00 01  00 00 00 00 00 00 00 00  |................|
 00000020  00 00 00 00 00 00 00 02                           |........|
 00000028

 udit@udit-Dabba ~$ hexdump -C data2.txt
 00000000  00 26 00 26 00 00 00 01  00 00 00 02 34 12 00 65  |.&.&........4..e|
 00000010  00 34 00 00 61 62 63 64                           |.4..abcd|
 00000018

 udit@udit-Dabba ~$ hexdump -C data3.txt
 00000000  60 00 00 00 00 8c 06 00  00 00 00 00 00 00 00 00  |`...............|
 00000010  00 00 00 00 00 00 00 01  00 00 00 00 00 00 00 00  |................|
 00000020  00 00 00 00 00 00 00 02  00 78 f8 65 00 00 00 02  |.........x.e....|
 00000030  f4 1f 96 00 18 34 a6 bf  1c 03 96 00 88 f1 90 08  |.....4..........|
 00000040

为什么data2.txt的内容没有复制到data3.txt???如果还有其他可行的办法请告诉我!!!!提前感谢...

最佳答案

Why contents of data2.txt are not copied to data3.txt?

strcat 专门用于连接 C 字符串,并且仅复制到空终止符为止。因此,一旦遇到 00,它就会停止从源复制,它认为 00 是字符串的结尾。请注意 data2 如何以 00 开头,因此它立即停止。

您需要 memcpy目标为 data3 中最后一个字节之后的 1,源为 data2。如果 data3(实际上是 data1)没有足够的空间来容纳 data2,您还需要优雅地失败。

关于c - strcat 给出意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7726443/

相关文章:

c - 如何从文件中读取数字并计算平均值?

C 指针数组随机改变地址

pointers - 语法错误: missing ';' before '*' when creating a pointer object of a user defined abstract class

为 cout 取消引用指针时的 C++ SegFault

c - 当我将图中的节点数从 4 增加到大于 5 时,malloc 会导致内存损坏

将字符转换为 C 中跳转表的索引

c - 真正基本的 mpir 问题

c - C语言中使用scanf读取文件

ruby-on-rails - 如何在不调用依赖 : :destroy on associations 的情况下销毁 Rails 模型

C: listen() API 返回 -1