aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMikkel Thestrup <mithe24@student.sdu.dk>2025-12-04 16:46:25 +0100
committerMikkel Thestrup <mithe24@student.sdu.dk>2025-12-04 16:46:25 +0100
commit99df63cc27d34b9eee3c41a4ab43dfc3362ec949 (patch)
treee3ab489445a945eabb14fb5192f64043efe98951
parente8311ffc4b271abb982799308a91094e8154039d (diff)
downloadcycle-detector-99df63cc27d34b9eee3c41a4ab43dfc3362ec949.tar.gz
cycle-detector-99df63cc27d34b9eee3c41a4ab43dfc3362ec949.zip
made graph_read() cleaner
Diffstat (limited to '')
-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;
}