I have to optimize my reading from a text file. How can I do that ? What is the best way to read from a file?
Printable View
I have to optimize my reading from a text file. How can I do that ? What is the best way to read from a file?
Use fgets() in a while loop.
yes... but will it run more faster. I hate to process the line to obtain what I want. Isn't it better to use fscanf() (i have to use it twice in order to read a char[] and an int ) ?
Why don't you try what Salem said, and when you have it working you can then do some profiling on the software while it runs - if, and only if, you are not satisfied with the speed, then you can take measures to increase the speed. No sense in optimising if the software will do everything you expect of it in the first place.
> I hate to process the line to obtain what I want. Isn't it better to use fscanf()
1. Reading from disk is about a million times slower than reading from memory, so what you use to read from the file is pretty much irrelevant. They all suck on the performance front.
2. Anything which attempts input AND conversion at the same time has simply horrible error recovery. What if your conversion fails on the int?
fgets just reads a line from the file and stores it in a buffer - no mess, no fuss and perfectly predictable. If there's a problem or end of file, then it's dead easy to drop out of the loop.Code:char buff[BUFSIZ];
char mystring[BUFSIZ];
int myint;
while ( fgets( buff, BUFSIZ, fp ) != NULL ) {
if ( sscanf( buff, "%s %d", mystring, &myint ) == 2 ) {
// success
} else {
// error in conversion
}
}
sscanf does the conversion, and if the number of conversions is as expected, then count it as success.
Of course if you wanted to be super-safe, you would use strtol() say to convert the integer. It can detect integer overflow whereas sscanf() cannot.
> yes... but will it run more faster.
You've got to make it right before you can make it fast.
thank you salem for explaining.