-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.c
97 lines (77 loc) · 2.32 KB
/
file.c
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
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <stdio.h>
#include <ctype.h>
#include "file.h"
#include "store.h"
graph_t file_read(char *file_name, int *rows, int *columns) {
/* Format pliku
Linijka 0: liczba_wierszy liczba_kolumn
Linijka 1: wierzchołek1 :waga1 wierzchołek2 :waga2 ... wierzchołekn :wagan
Linijka 1 przetrzymuje polaczenia wierzcholka 0,
linijka 2 przetrzymuje polaczenia wierzcholka 1,
linijka n przetrzymuje polaczenia wierzcholka n-1;
*/
FILE *in = fopen(file_name, "r");
graph_t g;
edge_t edge;
int line = 0, vertex;
double weight;
if (in == NULL) {
lastError = READ_ERR;
return NULL;
}
if (fscanf(in, "%d %d\n", rows, columns) < 2) {
fclose(in);
lastError = FORMAT_ERR;
return NULL;
}
g = store_init(*rows, *columns);
if (g == NULL) {
fclose(in);
lastError = MEMORY_ERR;
return NULL;
}
edge = g->edge;
int newline_indicator;
while (fscanf(in, "%d :%lf", &vertex, &weight) == 2) {
// Szukam znaku nowej linii
// Jezeli po wadze bedzie opis kolejnego wierzcholka przesuwam kursor
// o 1 pozycje w pliku w lewo
if (store_add_edge (edge, vertex, weight, line) != 0) {
return NULL;
}
while ( (newline_indicator = fgetc(in)) != EOF && isspace(newline_indicator)) {
if (newline_indicator == '\n') {
line++;
}
}
// newline_indicator jest EOF albo nie jest znakiem bialym
fseek(in, -1, SEEK_CUR);
}
fclose(in);
return g;
}
int file_create(char *file_name, graph_t g) {
FILE *out = fopen (file_name, "w");
edge_t edge = g->edge;
int n_vertices = g->rows * g->columns;
if (out == NULL) {
lastError = WRITE_ERR;
return 1;
}
fprintf (out, "%d %d\n", g->rows, g->columns);
for (int i = 0; i < n_vertices; i++) {
if (edge[i].weight == -1) {
fprintf (out, "\n");
continue;
}
fprintf (out, "%d :%.16lf ", edge[i].vertex_index, edge[i].weight);
edge_t tmp = edge[i].next;
while (tmp != NULL) {
fprintf (out, "%d :%.16lf ", tmp->vertex_index, tmp->weight);
tmp = tmp->next;
}
fprintf (out, "\n");
}
fclose (out);
return 0;
}