Another File question
If this has been answered, forgive me.
I have a series of files that I need to read in. I only care about the first field (seperated by spaces) on each line and each line is varying lengths.
Is there a way to use fscanf to read in the part I want and then move the file position pointer to the next line?
0200 this is the total number of widgets we need
0030 this can be what ever
Currently a fgets is being used and the data read is just trashed, it just seems there would be a better way than doing a disk read for no reason. Is there?
// and so on
No, those are C.
Use getline with an std::string to read line-by-line. You can then convert the string using atoi which will convert the string until it encounters non-numbers and then stops.
Excellent. Thank you for that.
Can I just recommend that if we should be using a standard C [rather than C++ style stringstream, which indeed does seem a bit excessive], that instead of using "atoi", you use strtol(), which is a more competent (as in, it supports a bunch more features) and less error-prone function (as in, it accepts bad data gracefully and predictably, particularly when it comes to for example overflows - you get the highest/smallest number possible [INT_MAX/INT_MIN respectively], rather than "some random number that is anywhere between 0 and INT_MAX"
Ah yes, atoi is C too, isn't it? >_<
So the correct way would be to use the string streams or just go C with strtol.
Yes, atoi() is an "before ANSI" type function, so it assumes most of the validation and checking is part of the programmers/users responsibility [although modern C-libraries MAY implement it as a call strtol() - for example GNU C library]. strtol is part of the ANSI standard library, so a bit more modern and robust.
Originally Posted by Elysia
Remember, C was originally written for PDP-11 running Unix. PDP-11 has a 32KWord address space [64KB] for each application, so many of the early functions were rather rudimentary to not take up too much space.