search

Home  >  Q&A  >  body text

c++ - 过于结构体,存进char *的buff,再写入文件

struct data
{
    u_short sin_port;
    struct  in_addr sin_addr;
    unsigned char id;
};

struct data Data[141];

char *buf,*buf1,
buf1 = (char *)malloc(10000);
memset(buf1, 0, 10000);

for (i =0;i< 141;i++)
 {
        memcpy(buf1, &Data[i].id,20);
        printf("buf11: %x\n", buf1);
        buf1+=20;
        memcpy(buf1, &Data[i].sin_addr, 4);
        buf1+=4;
        memcpy(buf1, &Data[i].sin_port, 2);
        buf1+=2;
        size1 += 26;
 }
 buf1 -= size1;
   
write(fd2, buf1, size1+1);
close(fd2);
free(buf1);

我发现这样写入的数据总是不对/?请教哪里有问题啊?一般都是先写入buffer,再写入文件?

天蓬老师天蓬老师2773 days ago444

reply all(4)I'll reply

  • 天蓬老师

    天蓬老师2017-04-17 14:52:46

    buf1 is a string type and should have a terminator ‘0’ at the end, otherwise there will be garbled characters.

    reply
    0
  • 阿神

    阿神2017-04-17 14:52:46

    1. The title "Too Structure" should be "For Structure"
    2. "char buf, buf1,", it is best to end with a Western semicolon.
    3. Please refer to the standard manual for the specific meaning of memory copy memcpy. According to your opinion, it should be a problem with the third parameter of this function.

    ……

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 14:52:46

    Initialize buf = buf1 before assignment and save the starting position of the data
    Finally use buf instead of buf1 to write the data write(fd2, buf, size1+1);
    buf1 -= size1 is also redundant processing

    reply
    0
  • 阿神

    阿神2017-04-17 14:52:46

    Don’t be so troublesome. You take a struct pointer, pointing to the "position of the buf pointer after strong transformation", and then assign the value of the struct you want to copy.
    char* buf = new char[100];
    struct Data d1; // init d1
    struct Data d2 = (struct Data)buf;
    *d2 = d1 ;

    This is the previous corresponding byte space of buf space, which stores the value of d1

    reply
    0
  • Cancelreply