I'm debugging some legacy code. It is using fscanf and the [] format specifiers to read some tilde (~) separated values. The file format is simple - value~value. value can be all spaces. If the first value is all spaces, it fails. Below is a stripped down sample...
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char b1[100], b2[100];
FILE *fp = fopen( "temp_out", "r" );
for ( int i = 0; i < 6; i++ )
{
int n = fscanf( fp, "%[^~]~%[^\n]\n", b1, b2 );
printf("fscanf converted %d '%s' '%s'\n", n, n>0?b1:"",n>1?b2:"");
}
fclose( fp );
}
And my input file is...
line1~blah
~blah2
blah~
This is compiled with gcc 8.4.1 on RedHat.
If I run it, I get...
fscanf converted 2 'line1' 'blah'
fscanf converted 0 '' ''
fscanf converted 0 '' ''
fscanf converted 0 '' ''
fscanf converted 0 '' ''
fscanf converted 0 '' ''
Only the first line is converted.
However, if I swap the first 2 input lines...
~blah2
line1~blah
blah~
It works...
fscanf converted 2 ' ' 'blah2'
fscanf converted 2 'line1' 'blah'
fscanf converted 2 'blah' ' '
fscanf converted 0 '' ''
fscanf converted 0 '' ''
fscanf converted 0 '' ''
I can put that line in a string and sscanf works. I can use fgets+sscanf, and that works, so that is a work around, but this pattern is used everywhere in the legacy code and I'd like to know what gives.
Any ideas?