Tcl Source Code

Artifact [91f3ee7e87]
Login

Artifact 91f3ee7e87d485d493b0327c29469acd369d4f89d64a23027b0a8844f41e3fbd:

Attachment "cscan.c" to ticket [85b7226da1] added by griffin 2023-09-21 17:12:22.
#include <stdio.h>
#include <errno.h>
#include <string.h>

int main(int argc, char **argv)
{
    int i;
    if (argc<3) {
	printf("usage: %s <string-value> <format-string> <value-type:(i|b|d|f|c)>\n"
	       "Uninitialized variables have value of -777, -7.77, or \"BAAD\"\n",
	       argv[0]);
	return 0;
    }
    for(i=1; i<argc; i+=3) {
	int status;
	char *str = argv[i];
	char *fmt = argv[i+1];
	char *type = argv[i+2];
	int ival;
	char cval;
	double dval;
	float fval;
	char remainder[4092];
	char fmtbuffer[4092];
	sprintf(fmtbuffer, "%s%%s", fmt);
	ival = -777;
	dval = -7.77;
	fval = -7.77;
	strncpy(remainder,"BAAD",4);
	switch (type[0]) {
	case 'i':
	case 'b':
	    status = sscanf(str, fmtbuffer, &ival, &remainder);
	    if (status < 0) {
		perror("Error: sscanf returned 0\n");
	    } else {
		printf("sscanf(\"%s\", \"%s\", &%s, &remainder) -> returned %d, results %s=%d remainder=\"%s\"\n",
		       str, fmtbuffer, type, status, type, ival, remainder);
	    }
	    break;
	case 'f':
	    status = sscanf(str, fmtbuffer, &fval, &remainder);
	    if (status < 0) {
		perror("Error: sscanf returned 0\n");
	    } else {
		printf("sscanf(\"%s\", \"%s\", &%s, &remainder) -> returned %d, results %s=%f remainder=\"%s\"\n",
		       str, fmtbuffer, type, status, type, fval, remainder);
	    }
	    break;
	case 'd':
	case 'l':
	    status = sscanf(str, fmtbuffer, &dval, &remainder);
	    if (status < 0) {
		perror("Error: sscanf returned 0\n");
	    } else {
		printf("sscanf(\"%s\", \"%s\", &%s, &remainder) -> returned %d, results %s=%f remainder=\"%s\"\n",
		       str, fmtbuffer, type, status, type, dval, remainder);
	    }
	    break;
	case 'c':
	    status = sscanf(str, fmtbuffer, &cval, &remainder);
	    if (status < 0) {
		perror("Error: sscanf returned 0\n");
	    } else {
		printf("(%d) %s -> %c \"%s\"\n", status, str, cval, remainder);
	    }
	    break;
	default:
	    printf("Unknown type: %s\n", type);
	    break;
	}
    }
}