CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    May 2018
    Posts
    158

    send structure via text protocol to network socket

    In Ansi C std C89 I want to send the following structure using text protocol via TCP network socket

    char text[1024];

    Code:
    struct Prot {
       char id[4];
       char type[2];
       int dim;
    } dato;
    sprintf(text, "%s %s %d", dato.id, dato.type, dato.dim);

    I want to use fix dimension every time I send this structure; my doubt is about int data because I know dimension of first 2 field (4 +2) id+type but I don't know how code this data into text to have fixed dimension,
    E.g.

    "AA BBBB 2"

    AA BBBB 1245"

    these strings have different dimensions depend of int value of 3rd field.

    if I fixed 10 as maximum string length I'll got 4 char for my string but how to code this data into string so that receiver can always read 10 characters and understand all data?

  2. #2
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: send structure via text protocol to network socket

    Why not specify a fixed width format, Possibly something like (not tried):

    Code:
    sprintf(text, "%4s %2s %10d", dato.id, dato.type, dato.dim);
    Also, shouldn't the struct be:

    Code:
    struct Prot {
       char id[5];
       char type[3];
       int dim;
    } dato;
    to allow for the null termination char?
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  3. #3
    Join Date
    May 2018
    Posts
    158

    Re: send structure via text protocol to network socket

    It's good idea I'll try It. Thanks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured