Refactoring the load_matrix function

This commit is contained in:
Denis Nuțiu 2016-04-28 10:29:15 +03:00
parent 57f68bf930
commit 2ddd1e2826
2 changed files with 26 additions and 25 deletions

View file

@ -5,7 +5,13 @@
int city_distance[5][5]; int city_distance[5][5];
char *cities[] = {"Timisoara", "Oradea", "Cluj", "Iasi", "Bucuresti"}; char *cities[] = {"Timisoara", "Oradea", "Cluj", "Iasi", "Bucuresti"};
void load_matrix(FILE * file) { void load_matrix(char * filename) {
FILE * file;
if ( !(file = fopen(filename, "r")) ) {
fprintf(stderr, "Can't open: %s\n", filename);
exit(errno);
}
int t, o, c, i, b; // timisoara, oradea ... int t, o, c, i, b; // timisoara, oradea ...
for (int j = 0; fscanf(file, "%d %d %d %d %d\n", &t, &o, &c, &i, &b) == 5; j++ ) { for (int j = 0; fscanf(file, "%d %d %d %d %d\n", &t, &o, &c, &i, &b) == 5; j++ ) {
city_distance[j][0] = t; city_distance[j][0] = t;
@ -14,6 +20,11 @@ void load_matrix(FILE * file) {
city_distance[j][3] = i; city_distance[j][3] = i;
city_distance[j][4] = b; city_distance[j][4] = b;
} }
if ( fclose(file) ) {
perror("File can't be closed!");
exit(errno);
}
} }
int find_min_index(int arr[], size_t size) { int find_min_index(int arr[], size_t size) {
@ -69,18 +80,7 @@ void print_matrix() {
} }
int main(void) { int main(void) {
FILE * file; load_matrix("mat.txt");
if ( !(file = fopen("mat.txt", "r")) ) {
perror("Can't open file!");
return errno;
}
load_matrix(file);
find_closest_path_from(1); // 1 - oradea; find_closest_path_from(1); // 1 - oradea;
if ( fclose(file) ) {
perror("File can't be closed!");
return errno;
}
return 0; return 0;
} }

View file

@ -5,7 +5,13 @@
int city_distance[5][5]; int city_distance[5][5];
char *cities[] = {"Timisoara", "Oradea", "Cluj", "Iasi", "Bucuresti"}; char *cities[] = {"Timisoara", "Oradea", "Cluj", "Iasi", "Bucuresti"};
void load_matrix(FILE * file) { void load_matrix(char * filename) {
FILE * file;
if ( !(file = fopen(filename, "r")) ) {
fprintf(stderr, "Can't open: %s\n", filename);
exit(errno);
}
int t, o, c, i, b; // timisoara, oradea ... int t, o, c, i, b; // timisoara, oradea ...
for (int j = 0; fscanf(file, "%d %d %d %d %d\n", &t, &o, &c, &i, &b) == 5; j++ ) { for (int j = 0; fscanf(file, "%d %d %d %d %d\n", &t, &o, &c, &i, &b) == 5; j++ ) {
city_distance[j][0] = t; city_distance[j][0] = t;
@ -14,6 +20,11 @@ void load_matrix(FILE * file) {
city_distance[j][3] = i; city_distance[j][3] = i;
city_distance[j][4] = b; city_distance[j][4] = b;
} }
if ( fclose(file) ) {
perror("File can't be closed!");
exit(errno);
}
} }
void do_all_routes2() { void do_all_routes2() {
@ -76,19 +87,9 @@ void do_all_routes() {
} }
int main(void) { int main(void) {
FILE * file; load_matrix("mat.txt");
if ( !(file = fopen("mat.txt", "r")) ) {
perror("Can't open file!");
return errno;
}
load_matrix(file);
// do_all_routes(); // do_all_routes();
do_all_routes2(); do_all_routes2();
if ( fclose(file) ) {
perror("File can't be closed!");
return errno;
}
return 0; return 0;
} }