fscanf() 显示意外行为

问题描述

我正在尝试读取 .txt 文件并将其转换为我之前成功实现和测试的图形结构。我正在使用 fscanf 函数,因此读取特定值变得更容易。代码如下:

int readGraph(char* fileName,Graph* graph) {
FILE* filePointer;
int nodes,edges;

filePointer = fopen(fileName,"r");
if(!filePointer) {
    fprintf(stderr,"[READ-GRAPH] Unable to open file");
    return(0);
}

if(fscanf(filePointer,"%d %d",&nodes,&edges) != 2)
    return (0);
initialize(graph,nodes);

int fromNode,toNode;
Weight weight;
while((fscanf(filePointer,"%d %d %f",&fromNode,&toNode,&weight)) != EOF) {
    printf("fromNode value %d toNode value %d weight value %f\n",fromNode,toNode,weight);
    addEdge(graph,weight);
}

fclose(filePointer);
return (1);}

int main() {

    Graph graph;
    readGraph((char*) filename,&graph);
    print(&graph);
}

每行包含两个节点值和一个浮点权重(第一行除外,它包含所需的节点和边数)。问题是,在读取 'grafo1.txt' 时,我会在某个时候得到垃圾值。此外,使用文件 'grafo.txt' 读取甚至没有完成(它打印到第 6 行然后程序崩溃)。

grafo.txt:
4 7
0 3 6.3
2 1 5.0
2 0 9
1 3 1.7
0 1 9
3 1 5.6
0 2 7.2

grafo1.txt
5 4
1 3 5.3
3 2 2
1 2 7.8
4 3 6

grafo1.txt output
fromNode value 1 toNode value 3 weight value 5.300000
fromNode value 3 toNode value 2 weight value 2.000000
fromNode value 1 toNode value 2 weight value 7.800000
fromNode value 4 toNode value 3 weight value 6.000000
[PRINT] Node 0
Connections:
[PRINT] Node 1
Connections: 2 (weight 7.800000),3 (weight 5.300000),[PRINT] Node 2
Connections:
[PRINT] Node 3
Connections: 2 (weight -463590750420992.000000),<- Garbage value. Why?
[PRINT] Node 4
Connections: 3 (weight 6.000000),grafo.txt output
fromNode value 0 toNode value 3 weight value 6.300000
fromNode value 2 toNode value 1 weight value 5.000000
fromNode value 2 toNode value 0 weight value 9.000000
fromNode value 1 toNode value 3 weight value 1.700000
<- it crashes after this blank line

我真的不明白为什么两个格式相同的 .txt 会给出不同的输出,而且:为什么只有其中一个能够几乎成功地创建图形? (几乎是因为在某些时候由于某种原因注册垃圾值)。任何帮助表示赞赏,我正在努力学习关于 C 的一切。

解决方法

正如 Jayr 指出的,问题与 readGraph 函数无关。谢谢杰尔。