I'm trying to read a graph file (.gr) with fscanf in the code below
#include<stdio.h>
int main( int argc, char** argv)
{
FILE *fp;
static char *input_file_name;
int size, edges, source, target, weight;
printf("Reading Graph File\n");
printf("argc=%d\n", argc);
if (argc == 2 )
{
input_file_name = argv[1];
printf("Input file: %s\n", input_file_name);
}
else
{
input_file_name = "../beleg/resources/sampleGraph-1.gr";
printf("No input file specified, defaulting to %s\n", input_file_name);
}
//Read in Graph from a file
fp = fopen(input_file_name,"r");
if(!fp)
printf("Error Reading Graph File\n");
while (!feof(fp))
{
if(fscanf(fp, "%*s %*s %d %d", &size, &edges))
printf("(first line) size=%d edges=%d\n", size, edges);
if(fscanf(fp, "%*s %d %d %d ", &source, &target, &weight))
printf("arc from %d to %d weight %d\n", source, target, weight);
}
return 0;
}
Here is a sample graph file, with p=init size, c=comment and a=arc
p sp 6 9
c graph contains 6 nodes and 9 arcs
c
a 1 2 7
a 1 3 9
a 1 6 14
c
a 2 3 10
a 2 4 15
c
a 3 4 11
a 3 6 2
c
a 4 5 6
c
a 5 6 9
c
a 6 5 16
The goal is to retrieve the init line and all arc lines like this:
...
(first line) size=6 edges=9
arc from 1 to 2 weight 7
arc from 1 to 3 weight 9
arc from 1 to 6 weight 14
...
arc from 6 to 5 weight 16
However the real output is:
...
(first line) size=6 edges=9
arc from 22050 to 1852102336 weight 22050
(first line) size=6 edges=9
arc from 22050 to 1852102336 weight 22050
arc from 22050 to 1852102336 weight 22050
(first line) size=1 edges=2
arc from 22050 to 1852102336 weight 22050
(first line) size=3 edges=9
arc from 1 to 6 weight 14
(first line) size=2 edges=3
arc from 1 to 6 weight 14
(first line) size=4 edges=15
arc from 1 to 6 weight 14
(first line) size=4 edges=11
arc from 3 to 6 weight 2
(first line) size=4 edges=5
arc from 3 to 6 weight 2
(first line) size=5 edges=6
arc from 3 to 6 weight 2
(first line) size=6 edges=5
arc from 3 to 6 weight 2
- I'd like to understand why there is this difference between expectation and real result.
- And then how to fix the code to get only init and arc lines.