Show me a test on the same equipment, where fscanf is slower than fgets + parsing out the data from the fgets buffer.
You can't, period.
Wow, I can't? period??
Ok. I used this program to fill a file with 10 million lines:
Code:
#include <stdio.h>
int main(void)
{
FILE* f = fopen ("./data", "w");
unsigned int i;
for(i = 0; i < 10000000; ++i)
fprintf(f, "%d %d %d\n", i, i, i);
fclose(f);
}
I then used the following code to read the data out. Note that there is a slow() function (using fscanf), and a fast method (custom code):
Code:
#include <stdio.h>
#include <ctype.h>
void slow(void)
{
FILE* f = fopen("./data", "r");
int first, second, third;
int counter = 0;
while(fscanf(f, "%d %d %d", &first, &second, &third) != EOF)
{
counter++;
}
printf("Got %d entries\n", counter);
}
int get_value(const char** pp)
{
const char* p = *pp;
int value = 0;
while(isdigit(*p))
{
value *= 10;
value += *p++ - '0';
}
*pp = p + 1; /* Add 1 to skip space */
return value;
}
void fast(void)
{
FILE* f = fopen("./data", "r");
int first, second, third;
int counter = 0;
char buffer[128];
int value;
while(fgets(buffer, sizeof(buffer), f))
{
const char* p = buffer;
first = get_value(&p);
second = get_value(&p);
third = get_value(&p);
counter++;
}
printf("Got %d entries\n", counter);
}
int main(void)
{
slow();
return 0;
}
The slow method took 9.52 seconds, the fast method took 1.73 seconds. This is using GCC 4.01 with optimizations turned on.