Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I haven't run timing test on your code, but I'll bet a nickel that the problems is using malloc(). That is SLOW. </p> <p>What Bart means is that a char[] array can contain multiple strings, back-to-back. If you scan through the array as a single string once, changing all ',' characters to '\0', your last line would look like:</p> <pre><code>{ '2', '5', 0, 0, '4', '5', 0, ? rest of buffer } ^ ^ ^ ! </code></pre> <p>The ^ carets below mark the positions where you'd record pointers to three strings. As you can see, they are equivalent to separate strings of "25", "", "45" in separate arrays. The ! below marks the 0 that ended the original string. Nothing beyond that has any meaning.</p> <p>All this depends on being able to modify the original string in-place, probably rendering it useless for any further processing (like printing out the offending line if an invalid field is detected). However, you are already copying the original buffer for local use, so that shouldn't be a problem. I'd get rid of the malloc for that copy buffer too, by the way.</p> <p>Code might look like:</p> <pre><code>while (fgets(line, 1024, stream)) { char tmp[sizeof line]; /* this will save a malloc()/free() pair */ char *tok, *fence, *pstr; char ch, *cp1=line, *cp2=tmp; while (0 != (ch = *cp1++)) *cp2++ = (ch == ',') ? 0 : ch; fence = cp2; /* remember end of string */ *fence = 0; /* and terminate final string */ tok = tmp; /* point to first token */ num1 =strtol(tok, &amp;pstr, 10); if (tok &lt; fence) tok += strlen(tok) + 1; num2 =strtol(tok,&amp;pstr,10); if (tok &lt; fence) tok += strlen(tok) + 1; num3 =strtol(tok,&amp;pstr,10); printf("Fields 1,2,3 would be 1=%d 2=%d 3=%d\n", num1,num2,num3); } </code></pre> <p>Obviously you don't need a 1K buffer to handle three values, so there will be a loop to pull out the values. The if statement after the first two strtol() calls is your replacement for getfield(), which isn't needed any more.</p> <p>After this is working, look at data validation. Nothing in this (or in the original) will detect invalid numbers. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload