fscanf Power

I recently had to read in a text file in order to draw some geometry on screen. Take a quick look at the text file:

Click to Show SelectShow


Lets assume for some reason we need to parse this text file and grab the float values from within. This isn’t a very difficult thing to do, it’s really just a matter of how much code I want to write. The best way I could think of doing this with C++ file i/o was to write something like:

Now whether or not this code is good or bad doesn’t really matter so much. The point is, I had to write an annoying amount of code just to grab the first float, and no matter the C++ technique used I don’t think code will be any less annoying to write. In the end all I really want is to read in these floats and just quickly parse a text file with a similar format whenever needed. Some hardcoding is to be expected, but I didn’t want to have to take the time writing code to jump through file offsets by burning through extraction assignments or manipulating the file pointer by hand. C++ file i/o is quite verbose.

I decided to look into some fscanf details to find something simpler that takes less code to write. Here’s what I learned from various parts of the internet:

Knowing this small amount of information is actually all that is needed in order to easily grab each float from the text file we need to parse. Lets take a look at the negation flag in conjunction with the negation scanset specifier:

This single line of code will read all text within our file until it comes across an equal sign. The equal sign will be left within the file. This small bit of fscanf knowledge is all that is needed in order to grab floats from our text file! Actually, one could take the automated serialization written about previously and have each member name be preceded by an equal sign. This equal sign character will make for writing a deserialization routine very simple! One could just call fscanf and immediately jump right before a value to grab.

The only issue is that the equal sign is still left within our file. A slight modification to the fscanf call can fix this:

The preceding equal sign will then read in an equal sign from the file. Now all that is left is a single call to fscanf to read in the float. Optionally you can place everything into one call like so:

And that’s it; a single line of fscanf code is all that’s needed to read over all text within our file in order to grab a float. The negation flag along with the negation scanset operator are awesome for writing file i/o operations, and the best part is that it’s more flexible than anything I can think of doing in C++ without writing tremendous amounts of code. I’ll likely be using C file i/o from now on whenever I can due to how non-verbose it is compared to C++ i/o.


Leave a Reply

Your email address will not be published. Required fields are marked *