aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--src/graph.c51
1 files changed, 34 insertions, 17 deletions
diff --git a/src/graph.c b/src/graph.c
index 11d6861..0a15f40 100644
--- a/src/graph.c
+++ b/src/graph.c
@@ -59,30 +59,47 @@ Graph *graph_read(const char *filename) {
FILE *file = fopen(filename, "r");
if (!file)
return NULL;
-
+
char line[1024];
- fgets(line, 1024, file);
-
+ if (!fgets(line, sizeof(line), file)) {
+ fclose(file);
+ return NULL;
+ }
+
int n = atoi(line);
- if (!n)
+ if (n <= 0) {
+ fclose(file);
return NULL;
+ }
+
Graph *g = graph_new(n);
-
- char c = line[0];
- int i = 0, j = 0;
- while (fgets(line, 1024, file)) {
- while (c != '\n') {
- if (c == '1') {
- graph_add_edge(g, i, j);
- j++;
- } else if (c == '0') {
- j++;
+ if (!g) {
+ fclose(file);
+ return NULL;
+ }
+
+ for (int i = 0; i < n; i++) {
+ if (!fgets(line, sizeof(line), file)) {
+ fprintf(stderr, "Error: Could not read row %d\n", i);
+ fclose(file);
+ return g;
+ }
+
+ int j = 0;
+ int col = 0;
+ while (col < n && line[j] != '\0' && line[j] != '\n') {
+ if (line[j] == '1') {
+ graph_add_edge(g, i, col);
+ col++;
+ } else if (line[j] == '0') {
+ col++;
}
- c++;
+ // skip any other characters
+ j++;
}
- i++;
}
-
+
+ fclose(file);
return g;
}