Advertisement
Guest User

Untitled

a guest
Apr 25th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct node
  5. {
  6. int id;
  7. char metal[40];
  8. int density;
  9. float price;
  10. struct node *next;
  11. };
  12.  
  13. int CheckOpen(FILE *fp);
  14. void ReadData(struct node *ptr, FILE *fp);
  15. void PrintData(struct node *ptr, int limit);
  16. void FreeMem(struct node *ptr);
  17. int Sorting1(const void * a, const void * b);
  18. int Sorting2(const void * a, const void * b);
  19.  
  20. int main(void)
  21. {
  22. FILE *fpread = fopen("5.csv", "r");
  23. CheckOpen(fpread);
  24. struct node *root;
  25. root = malloc(sizeof(struct node));
  26. ReadData(root, fpread);
  27. PrintData(root, 100);
  28. FreeMem(root);
  29. qsort(root, 100, sizeof(struct node *), Sorting1);
  30. printf("asdf");
  31. PrintData(root, 100);
  32. qsort(root, 100, sizeof(struct node *), Sorting2);
  33. PrintData(root, 3);
  34. fclose(fpread);
  35. return 0;
  36. }
  37.  
  38. int CheckOpen(FILE *fp)
  39. {
  40. if(fp == NULL)
  41. {
  42. printf("File not opened!\nExiting program!\n");
  43. return 0;
  44. }
  45. else
  46. {
  47. printf("File opened successfully!\n");
  48. return 1;
  49. }
  50. }
  51.  
  52. void ReadData(struct node *ptr, FILE *fp)
  53. {
  54. int i;
  55. char FirstLine[100];
  56. fgets(FirstLine, 100, fp);
  57. struct node *current;
  58. current = ptr;
  59. for (i = 0; i < 100; i++)
  60. {
  61. fscanf(fp, "%d,%[^,],%d,%f", &current->id,
  62. current->metal, &current->density, &current->price);
  63. if (i < 100)
  64. {
  65. current->next = malloc(sizeof(struct node));
  66. current = current->next;
  67. }
  68. }
  69. current->next = NULL;
  70. }
  71. void PrintData(struct node *ptr, int limit)
  72. {
  73. int i = 0;
  74. struct node *current;
  75. current = ptr;
  76. printf("id\tmetal\n");
  77. while (current->next != NULL && i < limit)
  78. {
  79. printf("%d, %s, %d, %f\n", current->id, current->metal,
  80. current->density, current->price);
  81. current = current -> next;
  82. i++;
  83. }
  84. }
  85. void FreeMem(struct node *ptr)
  86. {
  87. struct node *current;
  88. struct node *space;
  89. current = ptr;
  90. while(current != NULL)
  91. {
  92. space = current->next;
  93. free(current);
  94. current = space;
  95. }
  96. }
  97.  
  98. int Sorting1(const void * a, const void * b)
  99. {
  100. struct node *aa, *bb;
  101. aa = *(struct node **) a;
  102. bb = *(struct node **) b;
  103. return (aa->density - bb->density);
  104. }
  105.  
  106. int Sorting2(const void * a, const void * b)
  107. {
  108. struct node *aa, *bb;
  109. aa = *(struct node **) a;
  110. bb = *(struct node **) b;
  111. return (aa->price - bb->price);
  112. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement