In context – I’m writing a simple, standalone config file parser for a class that will go into a larger program. I understand that there are extremely effective libraries (such as BOOST) to do this for me, but the class must be strictly stand-alone (no external libraries).
So, I have a config file that may look a little like this:
output_file : some_output_file.root
input_file : input_file.txt
potential_file :
Notice that the potential_file entry is blank, and should be read as such.
I intend to use fscanf, with a format specifier
fscanf(cfg_file,"%s : %s\n",flag,value);
However, what happens in the case of the potential_file flag? Will the character string value be empty? Or will fscanf try to read the next available string in the file?
You should check return value of fscanf. It returns the number of arguments successfully parsed. It will not make an empty string for you if you have no space after colon in 3rd line as per pattern. It will stop parsing in that case. If you want to play safe with no extra checks, initialize value before fscanf.
%simplies reading of subsequent characters until a whitespace is found. The latter is defined as blank, newline, or tab. So it will not jump to next line.Also consider some library for config since you’ve tagged your questions in this way. YAML is easy to read and it has C bindings.