First of all there is nothing wrong with fscanf()
. The first thing you should know is that fscanf treats new line characters as white space. Thus, even though you look at the file as individual lines, fscanf sees it as:
setting1 = 1 setting2 = 2 setting3 = 3
This is NOT a problem, but it does affect how you might write fscanf code to read this text string. This next simple approach is much too simple?!
fscanf(fp, " setting1 = %d", &setting1);
fscanf(fp, " setting2 = %d", &setting2);
fscanf(fp, " setting3 = %d", &setting3);
Note. There is a leading space on the formats for fscanf
. This is so that the scanner can find none, one, or many white space characters. If the lines of the text file have leading spaces then a match will NOT be found unless that leading space is in the format. This makes perfect sense because the start of a line might have a few spaces.
Opening a file with read and append also works, when fscanf is coded correctly.
Get this to work. Now, is there more to the file than three settings? If so, then your fscanf code might have to be more complex, but maybe not. Remember the idea is to read data, if your code reads the data, then you're done.
Just for fun, I tried the following fscanfs:
fscanf(fp, " setting1 = %i ", &setting1);
fscanf(fp, "setting2 = %i ", &setting2);
fscanf(fp, "setting3 = %i", &setting3);
Notice that the "oddly placed spaces in the format definition allow for one or more white spaces between each of the keywords.
And one last comment. Your code should consider that a keyword might be misspelled by the user, in which case fscanf fails. Thus, always store or test the returned value from fscanf:
int x;
x = fscanf(fp, " setting1 = %d", &setting1);
if (x == 0) { // keyword setting1 was misspelled...
And for the trivia of the day:
x = fscanf(fp, " s e t t i n g 1 = %d", &setting1); // also works