How to make sure sscanf reads to the end of the line

I needed to do this for GNOME bug 453678, and it wasn’t very obvious. In the end I thought of a way, and I’ve tested it with gcc on GNU/Linux and HP C on OpenVMS to make sure it wasn’t just a GNU thing. (No, this doesn’t imply that I’m introducing a policy of building Metacity on OpenVMS in future.)

GEIN $ type test.c
#include <stdio.h>
#include <string.h>

void
check(char *string)
{
  int workspace = -1;
  int chars = 0;

  sscanf (string, "Workspace %d%n", &workspace, &chars);

  printf ("Input is [%s], workspace number is %d, fully=%s\n",
      string, workspace, *(string+chars)=='\0'?"Yes":"No");
}

int
main(int argc, char**argv)
{
  check ("Workspace 1 is very nice");
  check ("Workspace 2");
  check ("I like beer");
}

GEIN $ cc test
GEIN $ link test
GEIN $ run test
Input is [Workspace 1 is very nice], workspace number is 1, fully=No
Input is [Workspace 2], workspace number is 2, fully=Yes
Input is [I like beer], workspace number is -1, fully=No
GEIN $ 

OpenVMS testing courtesy of gein.vistech.net .

Published by

Thomas Thurman

Mostly themes, triaging, and patch review.

3 thoughts on “How to make sure sscanf reads to the end of the line”

  1. You could also use the fact that sscanf returns the number of fields successfully read. Put a dummy %c at the end of the format and check that
    the result is equal to the number of % fields before it:

    void
    check(char *string)
    {
    char dummy;
    int workspace ;

    int NB_FIELD=1 ;
    int nb = sscanf (string, “Workspace %d%c”, &workspace, &dummy);

    printf (“Input is [%s], fully=%s\n”,
    string, (nb==NB_FIELD) ? “Yes”:”No”);
    }

  2. Ah, I did spend a bit of time thinking about using the return value, but I hadn’t thought of the idea of using the dummy variable. Seems kind of obvious now you point it out :) Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *