Path: utzoo!utgpu!watmath!iuvax!uxc.cso.uiuc.edu!tank!mimsy!chris From: chris@mimsy.UUCP (Chris Torek) Newsgroups: comp.lang.c Subject: Re: Variable number of arguments to functions Keywords: how do i read a variable number of values? Message-ID: <18233@mimsy.UUCP> Date: 23 Jun 89 04:52:30 GMT References: <22380@iuvax.cs.indiana.edu> Distribution: na Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 57 In article <22380@iuvax.cs.indiana.edu> burleigh@silver.bacs.indiana.edu (Frank Burleigh) writes: >The vexing problem for me is that each pair of FILEA and FILEB >files has a different number of values on the input lines. I >could compile different versions of the program to accommodate >each pair, but that seems less than elegant. Indeed. >Apparently this is a problem to be solved by passing a variable >number of arguments to vscanf() and vprintf() with the va_... >macros in , but the procedures for this sort of >application are not clear to me (from KR2 or Turbo C reference). I do not know what led you to leap from `read a variable number of values' to `supply a variable argument list to an I/O function'. There is a much simpler way to read a variable number of values, and that is to make a variable number of read calls. For instance: #include #include #include #include #include ... long v; char *ptr, *eptr; FILE *stream; char buf[SIZE]; ... if (fgets(buf, sizeof(buf), stream) == NULL) { ... handle EOF or error ... } ptr = buf; for (i = 0; i < values_per_line; i++) { ptr = strspn(ptr, " \t"); /* or whatever */ if (ptr == NULL || *ptr == '#') { /* # => comment */ ... handle ran-out-of-values ... } errno = 0; v = strtol(ptr, &eptr, 0); if ((v == LONG_MIN || v == LONG_MAX) && errno == ERANGE) { ... handle value out of range ... } if (ptr == eptr) { ... handle no digits ... } } if (ptr) { ptr = strspn(ptr, " \t"); if (ptr && *ptr != '#') { ... handle too much on line ... } } -- In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163) Domain: chris@mimsy.umd.edu Path: uunet!mimsy!chris