1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
|
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "intList.h"
#include "intList.c"
typedef struct Edge {
int from, to;
double weight;
}Edge;
IntList* initedges(int n){
IntList* adjvertices = calloc(n+1,sizeof(IntList));
int itora;
for( itora = 0; itora <= n; itora++){
adjvertices[itora] = NULL;
}
return (adjvertices);
}
Edge parseedge(char* line){
Edge newedge;
int nwords = sscanf(line, " %d %d %f",&newedge.from, &newedge.to, &newedge.weight);
if(nwords < 2 || nwords > 3){
char tempo[1024];
perror(strcat(strcpy(tempo,"Bad edge: "), line));
exit(1);
}
if (nwords == 2) newedge.weight = 0.0;
return newedge;
}
int parsen(char* line){
int n;
if(sscanf(line, "%i", &n) != 1){
char temp[1024];
perror(strcat(strcpy(temp, "Bad line 1: "), line));
exit(1);
}
return n;
}
int loadedges(FILE* inbuf, IntList* adjvertices){
Edge newele;
int m = 0;
char *line;
fgets(line, sizeof(line), inbuf);
while(line!=NULL){
newele = parseedge(line);
adjvertices[newele.from] = cons(newele.to, adjvertices[newele.from]);
++m;
fgets(line, sizeof(line), inbuf);
}
return m;
}
int main(int argc, char* argv[]){
int a, b;
IntList* adjvert;
if(argc == 0){
printf("Usage: graph < input.data");
exit(0);
}
char *infile= argv[2];
FILE *inbuf = fopen(infile, "r");
printf("Opened %s for input.", infile);
char line[1024];
fgets(line, 1024, inbuf);
b = parsen(line);
printf("n = %d", b);
adjvert = initedges(b);
a = loadedges(inbuf, adjvert);
fclose(inbuf);
printf("m = %d", a);
int itor;
for(itor = 0; itor<=b; itor++){
printf("%d\t%s", itor, tostring(",",adjvert[itor]));
}
}
|