adjacent.c~ 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include "adjacent.h"
  4. void read_num_nodes(FILE *fptr, int *num_nodes){
  5. // read first value in file
  6. if((fscanf(fptr, "%d", num_nodes)) == EOF){
  7. return;
  8. }
  9. }
  10. void read_adjacent_nodes(FILE *fptr, int num_nodes, int **adjacent){
  11. // declare variables
  12. int a, b, c = 0; // store values
  13. int i = 0; // incrementor
  14. // ensure the fptr is at the beginning
  15. rewind(fptr);
  16. // allocate memory and move fptr to correct spot
  17. fscanf(fptr, "%d %d", &a, &b); // move past line 1
  18. //printf("%d %d\n", a, b); // for testing
  19. for(i = 0; i < num_nodes; i++){
  20. adjacent[i] = calloc(num_nodes, sizeof(int)); // init to 0
  21. fscanf(fptr, "%d\t%d\t%d", &a, &b, &c); // move through
  22. //printf("%d\t%d\t%d\n", a, b, c); // for testing
  23. }
  24. // scan relevent values
  25. while(fscanf(fptr, "%d %d", &a, &b) != EOF){
  26. //printf("%d %d\n", a, b); // for testing
  27. adjacent[a][b] = 1;
  28. adjacent[b][a] = 1;
  29. }
  30. }
  31. int main (int argc, char **argv){
  32. int num_nodes = 0;
  33. // open file for reading
  34. FILE *fptr = fopen(argv[1], "r");
  35. if (fptr == NULL){ // check for error
  36. printf("File name error.\n");
  37. return EXIT_FAILURE;
  38. }
  39. read_num_nodes(fptr, &num_nodes);
  40. int **adjacent = malloc(num_nodes * sizeof(int *));
  41. read_adjacent_nodes(fptr, num_nodes, adjacent);
  42. // print values in proper format
  43. int i = 0;
  44. int j = 0;
  45. for(i = 0; i < num_nodes; i++){
  46. printf("%d:", i);
  47. for(j = 0; j < num_nodes; j++){
  48. if(adjacent[i][j] > 0){
  49. printf(" %d", j);
  50. }
  51. }
  52. printf("\n");
  53. }
  54. // clean up
  55. for(i = 0; i < num_nodes; i++){
  56. free(adjacent[i]);
  57. }
  58. free(adjacent);
  59. fclose(fptr);
  60. return EXIT_SUCCESS;
  61. }