-2

I have a char* that contains the message below. The "movie.mjpeg" name is of variable length. How can I analyze the char* so that I can save the name of the movie and the CSeq number in another variable and then discard the char*.

SETUP movie.Mjpeg RTSP/1.0 CSeq: 1 Transport: RTP/TCP; interleaved=0

Patricio Jerí
  • 528
  • 2
  • 5
  • 15
  • It would help if you could please describe what the other parts can potentially contain. It's hard to tell without some further context. –  Apr 03 '13 at 07:09

2 Answers2

1

You can tokenise a string to extract specific fields, such as with:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char inpStr[] = "SETUP movie.Mjpeg RTSP/1.0 CSeq: 1"
                " Transport: RTP/TCP; interleaved=0";

int main (void) {
    char *name, *cseq;

    strtok (inpStr, " ");                  // SETUP
    name = strdup (strtok (NULL, " "));    // movie.Mjpeg

    strtok (NULL, " ");                    // RTSP/1.0
    strtok (NULL, " ");                    // CSeq:
    cseq = strdup (strtok (NULL, " "));    // 1

    printf ("Name is [%s], cseq is [%s]\n", name, cseq);

    free (name);
    free (cseq);

    return 0;
}

The output of this is:

Name is [movie.Mjpeg], cseq is [1]

Basically, each call to strtok will give you the address of the next token, suitably delimited. The call to strdup (a) will ensure you get a duplicate of the string rather than a pointer to the original string. Using a pointer to the original string would mean changes to one would affect the other.

Keep in mind this alters the original string so, if you don't want that, make sure you use a copy.


(a) Standard C does not provide strdup although it's available in many implementations. If your implementation doesn't have one, see here.

Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
0

Assuming the static fields are really static, you can use sscanf() to scan out the variable parts.

This has the benefit (?) of not relying on strtok() which is kind of a scary function (it modifies the input string). It also lets you convert non-string data in the same operation, which can be convenient.

const char *inpStr = "SETUP movie.Mjpeg RTSP/1.0 CSeq: 1 Transport: RTP/TCP; interleaved=0";
char  filename[128], transport[32];
int   cseq;

if(sscanf(inpStr, "SETUP %s RTSP/1.0 CSeq: %d Transport: %s;",
          filename, &cseq, transport) == 3)
{
  printf("Got filename '%s', cseq=%d, transport='%s'\n",
         filename, cseq, transport);
}

Note that checking the return value of sscanf() to ensure it really suceededed in converting all the fields is a good idea, otherwise you can't rely on the values being present.

unwind
  • 391,730
  • 64
  • 469
  • 606